Derek
Derek

Reputation: 11905

Wait on all promises in a promise chain

Is there a way to wait on all promises in a Promise chain? I have discovered the Promise.all() function for waiting on an array of promises, but I couldnt make that work.

I have something that is roughly like this

var returnPromise2;
var returnPromise1 = function1ThatReturnsAPromise.then(
    function onSuccess(array) {
       console.log("First function finished");
    }).then( function (value) {
          returnPromise2 = function2ThatReturnsAPromise(value);
    });
    return [returnPromise1, returnPromise2];

So in my calling code, if i do Promise.all(arrayOfPromises) I am able to get the value from returnPromise1, but not the 2nd one. The dillema being that at the time of the return, returnPromise2 is still null.

Any tips appreciated on how to approach this.

Upvotes: 2

Views: 2946

Answers (1)

jfriend00
jfriend00

Reputation: 708146

When inside a .then() handler, you have to return a promise if you want it to be linked into the chain and have its value become the fulfilled value.

Though it's not entirely clear to me from your question what you're trying to achieve, it seems like maybe what you want to do is this:

function1ThatReturnsAPromise().then(function(array) {
   console.log("First function finished");
   return array;
}).then(function(value) {
      return function2ThatReturnsAPromise(value);
}).then(function(finalValue) {
    // you can process the finalValue here which will be the last
    // value returned or the fulfilled value of the last promise returned
});

If you want to accumulate values from multiple promises, then there are several separate design patterns for that. Here are prior answers that show several different ways to do that.

Chaining Requests and Accumulating Promise Results

How do I access previous promise results in a .then() chain?

Upvotes: 3

Related Questions