简体   繁体   中英

Javascript promises inside promise

Let's say I have a function call that returns a value, I need to iterate through this value and do another function call that returns a result. I need to put all results in an array and display all values in the array when it's finished, for example something like this:

var myArray = [];
oneAsyncCall().then(function(val) {
    for (var i = 1; i < val; i++) {
        anotherAsyncCall()().then(function(result) {
            myArray.push(result);
        });
    }
});

Where should I do my foreach to iterate the myArray, when everything is finished?

You should do something like this. Make a promise array and use Promise.all

var myArray = [];
const promiseArray = [];

oneAsyncCall.then(function(val){
    for (var i = 1 ; i < val ; i++) {
        promiseArray.push(anotherAsyncCall()());
    }

    Promise.all(promiseArray)
      .then(function(dataArrayFromPromises){
           //do things with dataArray which is an array of data from promiseArray promises
       });
});

Use Promise.all . You can use ES6 Promise polyfill or bluebird.

oneAsyncCall()
.then(function(val) {
    var promises = [];
    for (var i = 1; i < val; i++) {
        promises.push(anotherAsyncCall()());
    }
    return Promise.all(promises);    
})
.then(function(myArray) {
    // you get all result here
});

Additionally, I use following to get rid of for statement.

Promise.all(
  Array(val-1).fill(undefined).map(() => anotherAsyncCall()())
)

So it can be rewritten as

oneAsyncCall()
.then((val) => Promise.all(
   Array(val-1).fill(undefined)
   .map(() => anotherAsyncCall()())
))

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