for await of 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 循环是否等待第一次迭代完成以调用下一个承诺?还是所有的承诺都同时触发,循环内部就像它们的回调?

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

只是为了澄清,

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.all是处理一系列承诺的唯一可行选择

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

有关详细信息,请参阅等待多个并发等待操作和等待 Promise.all(( 和多个等待之间的区别?

当在异步迭代器上当前迭代的计算依赖于以前的一些迭代时,需要for await ...。如果没有依赖关系,Promise.all是你的选择。for await构造旨在与异步迭代器一起使用,但 - 如您的示例,您可以将其与一系列 promise 一起使用。

有关使用无法使用Promise.all重写的异步迭代器的示例,请参阅书 javascript.info 中的示例分页数据:

(async () => {
for await (const commit of fetchCommits('javascript-tutorial/en.javascript.info')) {
console.log(commit.author.login);
}
})();

在这里,fetchCommits异步迭代器发出请求以fetchGitHub 存储库的提交。fetch以 30 次提交的 JSON 进行响应,并提供指向Link标头中下一页的链接。因此,下一次迭代只能在上一次迭代具有下一个请求的链接后启动

async function* fetchCommits(repo) {
let url = `https://api.github.com/repos/${repo}/commits`;
while (url) {
const response = await fetch(url, { 
headers: {'User-Agent': 'Our script'}, 
});
const body = await response.json(); // (array of commits
// The URL of the next page is in the headers, extract it using a regexp
let nextPage = response.headers.get('Link').match(/<(.*?)>; rel="next"/);
nextPage = nextPage?.[1];
url = nextPage;
for(let commit of body) { // yield commits one by one, until the page ends
yield commit;
}
}
}

正如您所说Promise.all将一次性发送所有请求,然后在所有请求完成后您将获得响应。

在第二种情况下,您将一次性发送请求,但逐个收到响应。

请参阅此小示例以供参考。

let i = 1;
function somethingAsync(time) {
console.log("fired");
return delay(time).then(() => Promise.resolve(i++));
}
const items = [1000, 2000, 3000, 4000];
function delay(time) {
return new Promise((resolve) => { 
setTimeout(resolve, time)
});
}
(async() => {
console.time("first way");
const promises = await Promise.all(items.map(e => somethingAsync(e)));
for (const res of promises) {
console.log(res);
}
console.timeEnd("first way");
i=1; //reset counter
console.time("second way");
for await (const res of items.map(e => somethingAsync(e))) {
// do some calculations
console.log(res);
}
console.timeEnd("second way");
})();

您也可以在这里尝试 - https://repl.it/repls/SuddenUselessAnalyst

希望这有帮助。

实际上,使用for await语法确实会立即触发所有承诺。

一小段代码证明了这一点:

const sleep = s => {
return new Promise(resolve => {
setTimeout(resolve, s * 1000);
});
}
const somethingAsync = async t => {
await sleep(t);
return t;
}
(async () => {
const items = [1, 2, 3, 4];
const now = Date.now();
for await (const res of items.map(e => somethingAsync(e))) {
console.log(res);
}
console.log("time: ", (Date.now() - now) / 1000);
})();

标准输出:time: 4.001

但是循环的内部不会充当"回调"。如果我反转数组,所有日志都会立即出现。我想承诺是立即触发的,运行时只是等待第一个解析进入下一次迭代。

编辑:实际上,当我们将其与异步迭代器以外的其他东西一起使用时,使用for await是一种不好的做法,最好是使用Promise.all,根据@Bergi在他的回答中。

最新更新