简体   繁体   English

Promise.all不等待所有诺言得到解决

[英]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. Promise.all没有等待所有的诺言得到解决。在下面的代码中,我试图复制一个场景,其中根据某些服务(两个服务)的响应,我将设置数组,然后在完成所有服务调用后进行处理。所有人都会给出自己的价值。 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 []" 它应该打印“ All done [1000,3000]”,但它打印“ All done []”

Please help. 请帮忙。

This happens because you are creating promises after the timeout. 发生这种情况是因为您在超时后创建了诺言。 You need to wrap the timeout in Promise instead 您需要将超时包装在Promise中

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. 将promise随超时一起推送到数组中将需要1和2秒,因此,如果您等待数组包含某些内容,例如,如果您也为promise设置了超时,那么您将得到想要的结果,这应该在应许被推入数组。

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);
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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