gpt4 book ai didi

node.js - nodejs,reduce中的异步,await不等待promise解析

转载 作者:行者123 更新时间:2023-12-02 03:21:28 24 4
gpt4 key购买 nike

我不明白为什么所有的 promise 都会同时得到解决。我读到 awaitforEach 循环中不能按预期工作,但它也不能与 map 一起工作

const promise = async (ms, name) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(`resolving ${name}`)
resolve(name)
}, ms)
});
}

async function main() {
['foo', 'bar', 'baz'].reduce(async (accum, curr) => {
const res = await promise(1000, curr)
return res
}, Promise.resolve(''))
}

main()

但是在这种情况下,await 工作得很好:

async function main2() {
const ms = 1000
await promise(ms, "foo")
await promise(ms, "bar")
await promise(ms, "baz")
}

main2()

最佳答案

reduce 回调的每次迭代都将同步初始化。在运行 reduce 回调主体之前,您需要等待上次迭代的累加器(幸运的是,这已经是一个 Promise)解析:

const promise = async (ms, name) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(`resolving ${name}`)
resolve(name)
}, ms)
});
}

async function main() {
['foo', 'bar', 'baz'].reduce(async (accum, curr) => {
// don't progress further until the last iteration has finished:
await accum;
const res = await promise(1000, curr)
return res
}, Promise.resolve(''))
}

main()

关于node.js - nodejs,reduce中的异步,await不等待promise解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54626136/

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