我正在尝试使用“ reduce”设置顺序解析,然后继续进行其他工作,但是它似乎并不在等待,而是继续进行。我如何等待阵列中的每个诺言完成?
function Work(data){
return new Promise((resolve)=>{resolve()});
}
function DoWork(data){
return new Promise((resolve, reject)=>{
setTimeout(() => {
Work(data)
.then(() => {
console.log("Doing work on '"+data+"'");
resolve();
})
.catch(err => {
console.log("Failed to do work on '"+data+"'");
reject(err);
});
}, 1000);
});
}
var AllMyWork= ["a","b","c"];
AllMyWork.reduce((p, data) => p.then(DoWork(data)), Promise.resolve())
.then(result => {
console.log("All work is finished");
})
.catch(err => {
console.log("MyArray reduce has failed");
});
这就是我得到的回报:
All work is finished
Doing work on 'a'
Doing work on 'b'
Doing work on 'c'
我想做的就是等所有工作都完成后再写msg“所有工作都完成了。”
答案 0 :(得分:2)
p.then(DoWork(data))
这会立即调用DoWork
。您要将函数传递给.then
:
p.then(() => DoWork(data))
否则减少就可以了。示例:
delay = ms => new Promise(resolve => setTimeout(resolve, ms));
DoWork = work => delay(1000).then(() => console.log("did work", work));
AllMyWork = ["a","b","c"];
AllMyWork.reduce((p, data) => p.then(() => DoWork(data)), Promise.resolve())
.then(result => {
console.log("All work is finished");
});