javascript – 如何在循环中返回许多Promise并等待它们全部做其他事情

我有一个循环调用一个异步执行的方法.这个循环可以多次调用该方法.在这个循环之后,我有另一个循环,只有在完成所有异步操作后才需要执行.所以这说明了我的愿望:

for(i=0;i<5;i++){
    doSomeAsyncStuff();    
}

for(i=0;i<5;i++){
    doSomeStuffOnlyWhenTheAsyncStuffIsFinish();    
}

我对承诺并不熟悉,所以有人能帮助我实现这一目标吗?

这就是我的doSomeAsyncStuff()行为:

doSomeAsyncStuff{
    var editor = generateCKEditor();
    editor.on('instanceReady',function(evt){
        doSomeStuff();
        // There should be the resolve() of the promises I think.
    })
}

也许我必须做那样的事情:

doSomeAsyncStuff{
    var editor = generateCKEditor();
    return new Promises(function(resolve,refuse){
        editor.on('instanceReady',function(evt){
            doSomeStuff();
            resolve(true);
        })
    }
}

但我不确定语法.

解决方法:

你可以使用Promise.all(spec,MDN):它接受一堆个人承诺并给你一个单一的承诺,当你给它的所有承诺得到解决,或者当它们中的任何一个被拒绝时被拒绝.

因此,如果你让doSomeAsyncStuff返回一个promise,那么:

var promises = [];

for(i=0;i<5;i+){
    promises.push(doSomeAsyncStuff());
}

Promise.all(promises)
    .then(() => {
        for(i=0;i<5;i+){
            doSomeStuffOnlyWhenTheAsyncStuffIsFinish();    
        }
    })
    .catch((e) => {
        // handle errors here
    });

Axel Rauschmayer有一篇关于承诺here的好文章.

这是一个例子 – live copy on Babel’s REPL

 function doSomethingAsync(value) {
      return new Promise((resolve) => {
        setTimeout(() => {
          console.log("Resolving " + value);
          resolve(value);
        }, Math.floor(Math.random() * 1000));
      });
    }
    
    function test() {
      let i;
      let promises = [];
      
      for (i = 0; i < 5; ++i) {
        promises.push(doSomethingAsync(i));
      }
      
      Promise.all(promises)
          .then((results) => {
            console.log("All done", results);
          })
          .catch((e) => {
              // Handle errors here
          });
    }
    
    test();

(没有打扰.catch,但你确实想要.catch在你的真实世界中,如前所示.)

样本输出(因为Math.random,首先完成的内容可能会有所不同):

Resolving 3
Resolving 2
Resolving 1
Resolving 4
Resolving 0
All done [0,1,2,3,4]

相关文章

最后的控制台返回空数组.控制台在ids.map函数完成之前运行va...
我正在尝试将rxJava与我已经知道的内容联系起来,特别是来自J...
config.jsconstconfig={base_url_api:"https://douban....
我正在阅读MDN中的javascript,并且遇到了这个谈论承诺并且不...
config.jsconstconfig={base_url_api:"https://douban....
这是我的代码main.cpp:#include<string>#include<...