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