gpt4 book ai didi

node.js - 等到顺序 promise 解决后再在 Node 中继续

转载 作者:太空宇宙 更新时间:2023-11-03 23:19:09 26 4
gpt4 key购买 nike

我正在尝试使用“reduce”设置顺序解析,然后继续做一些其他工作,但它似乎没有等待,它只是继续。如何等待数组中的每个 Promise 完成?

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'

我想做的是等到所有工作完成然后写入消息“所有工作已完成”。

最佳答案

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

关于node.js - 等到顺序 promise 解决后再在 Node 中继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51714438/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com