简体   繁体   中英

Promise.all is not waiting for all promises to get resolved

Promise.all is not waiting for all promises to get resolved.In Below code I am trying to replicate a scenarios where depending on some service (two services) response I would be setting the array and then when all service call is done, process.all will give the captrued value. However this does not work.

let errorPromises = [];
    setTimeout(() => {
      errorPromises.push(new Promise((resolve, reject) => resolve(1000)));
    }, 2000);
    setTimeout(() => {
      errorPromises.push(new Promise((resolve, reject) => resolve(3000)));
    }, 1000);

    let promise = Promise.all(errorPromises);
    promise.then(data => {
      console.log("All done", data);
    });

it should print "All done [1000,3000]" but it prints "All done []"

Please help.

This happens because you are creating promises after the timeout. You need to wrap the timeout in Promise instead

let errorPromises = [];

errorPromises.push(new Promise((resolve, reject) => {
  setTimeout(() => resolve(1000), 2000);
}));

// or a one-liner
// errorPromises.push(new Promise(resolve => setTimeout(() => resolve(1000), 2000)));

/// repeat with all others...

let promise = Promise.all(errorPromises);
promise.then(data => {
  console.log("All done", data);
});

This happens because you create the promise, before your error promises are in the array. It will take 1 and 2 seconds for the promises to be pushed in the array with timeout, so you get what you want if you wait that the array contains something, for example if you set timeout for the promise too, which should happen AFTER the promises are pushed in to the array.

let errorPromises = [];
    setTimeout(() => {
      errorPromises.push(new Promise((resolve, reject) => resolve(1000)));
    }, 2000);
    setTimeout(() => {
      errorPromises.push(new Promise((resolve, reject) => resolve(3000)));
    }, 1000);

    setTimeout(() => {
        let promise = Promise.all(errorPromises);
        promise.then(data => {
          console.log("All done", data);
        });
    }, 3000);

So basically you trigger the console log instantly, and then your array is still empty because of the timeout.

 let errorPromises = [];
 errorPromises.push(new Promise((resolve, reject) => resolve(1000)));
 errorPromises.push(new Promise((resolve, reject) => resolve(3000)));

 let promise = Promise.all(errorPromises);
 promise.then(data => {
  console.log("All done", data);
 });

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