等待VS Promise.all [英] for await of VS Promise.all

查看:92
本文介绍了等待VS Promise.all的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这之间有什么区别吗?

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
}

我知道在第一个代码段中,所有的诺言都在同一时间执行,但是我不确定第二个. for循环是否等待第一次迭代完成以调用下一个promise?还是所有的诺言都在同一时间触发,循环的内部就像它们的回调一样?

I know that in the first snippet, all the promises are fired at the same time but I'm not sure about the second. Does the for loop wait for the first iteration to be done to call the next promise ? Or are all the promises fired at the same time and the inside of the loop acts like a callback for them ?

推荐答案

是的,它们绝对是不同的. for await应该与异步迭代器一起使用,而不是与预先存在的promise数组一起使用.

Yes, they absolutely are different. for await is supposed to be used with asynchronous iterators, not with arrays of pre-existing promises.

只是要弄清楚,

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调用在等待任何内容之前立即立即进行.然后,将它们一个接一个地await,如果其中任何一个被拒绝,这肯定是一个问题:它将导致未处理的promise拒绝错误. 使用Promise.all是处理承诺的唯一可行选择:

The somethingAsync calls are happening immediately, all at once, before anything is awaited. Then, they are awaited one after another, which is definitely a problem if any one of them gets rejected: it will cause an unhandled promise rejection error. Using Promise.all is the only viable choice to deal with the array of promises:

for (const res of await Promise.all(promises)) …

请参见正在等待一个以上的并发await操作 await Promise.all()和多次await之间有什么区别吗? 以获得详细信息.

See Waiting for more than one concurrent await operation and Any difference between await Promise.all() and multiple await? for details.

这篇关于等待VS Promise.all的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆