我不明白为什么所有承诺都在同一时间得到解决的原因。
我读到await
在forEach
循环中无法正常工作,但在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()
答案 0 :(得分:2)
reduce
回调的每个迭代将同步初始化。您需要等待上一次迭代中的累加器(幸运的是已经是Promise
)才能解决,然后再运行reduce
回调的主体:
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()