0

Is it possible use a result from a promise in a future call without saving it off to the functions scope?

The code below does not work because I am trying to use "room" that was returned from a promise in a future function call. Any help would be awesome!

validate(roomId, String(user._id))
    .then( **room**       => buildMsgPacket(room, msgRequest.msg, user) )
    .then( msgPacket  => addToFirebase(msgPacket) )
    .then(()          => notifyRecipents(**room**, msgPacket))
Austin Lovell
  • 1,049
  • 3
  • 17
  • 29
  • You have to save the result somewhere to use it elsewhere in the promise chain. It's a function argument and without doing anything else is ONLY accessible within that function (that's just plain Javascript scoping rules). See [the question this was marked a dup of](http://stackoverflow.com/questions/28714298/how-to-chain-and-share-prior-results-with-promises) for a variety of ways to save the result to make it usable later in the chain. – jfriend00 Jun 23 '16 at 14:25
  • On second reading of your question, it almost appears you're asking how to use a value that has not yet been obtained and won't be obtained until later in the promise chain. There's NO way to do that ever. The value doesn't exist yet until you execute the function that retrieves it. Please tell me that's not what you're asking. – jfriend00 Jun 23 '16 at 14:27
  • To do something like what you're asking, you could pass around the promise and tack on another `then` at a later time. `var promise = validate(roomId, String(user._id)).then(...).then(...);` `function(promise) { promise.then( ... ) }`. You could only access the object in your `then` callback, and if you wanted to use it further, you'd have to return it from your callback, and tack on *yet another* `then`. Either that, or you could subscribe another listener to the `Recipents` list, and do your processing that needs `room` there. – Merlyn Morgan-Graham Jun 23 '16 at 14:32
  • @jfriend00 no your first response was correct. I was mainly curious if things may have changed with using the fat arrow. I wondered if the response from these promises were now being applied to scope of the function. – Austin Lovell Jun 23 '16 at 17:20

0 Answers0