简体   繁体   中英

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM