这之间有什么区别吗:
const promises = await Promise.all(items.map(e => somethingAsync(e)));
for (const res of promises) {
// do some calculations
}
还有这个?
for await (const res of items.map(e => somethingAsync(e))) {
// do some calculations
}
我知道在第一个片段中,所有 promise 都会同时触发,但我不确定第二个片段。 for 循环是否等待第一次迭代完成才能调用下一个 Promise?或者所有的 promise 都是同时触发的,并且循环内部就像它们的回调一样?
最佳答案
是的,它们绝对不同。 for wait
应该与异步迭代器一起使用,而不是与预先存在的 Promise 数组一起使用。
只是为了澄清,
for await (const res of items.map(e => somethingAsync(e))) …
工作原理与
相同const promises = items.map(e => somethingAsync(e));
for await (const res of promises) …
或
const promises = [somethingAsync(items[0]), somethingAsync(items[1]), …];
for await (const res of promises) …
在等待任何事情之前,somethingAsync
调用立即立即发生。然后,它们被一个接一个地等待,如果其中任何一个被拒绝,这肯定是一个问题:它将导致未处理的 promise 拒绝错误。 使用Promise.all
是处理 promise 数组的唯一可行选择:
for (const res of await Promise.all(promises)) …
参见Waiting for more than one concurrent await operation和 Any difference between await Promise.all() and multiple await?了解详情。
关于javascript - VS Promise.all 的等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59694309/