我目前有一个像这样的 for 循环:
async myFunc() {
for (l of myList) {
let res1 = await func1(l)
if (res1 == undefined) continue
let res2 = await func2(res1)
if (res2 == undefined) continue
if (res2 > 5) {
... and so on
}
}
}
问题是 func1、func2 是返回 promise 的网络调用,我不希望它们在等待它们时阻塞我的 for 循环。所以我不介意与 myList[0] 和 myList[1] 并行工作,也不关心列表项的处理顺序。
我怎样才能实现这个目标?
最佳答案
我会通过编写一个函数来处理您按顺序处理的一个值:
async function doOne(l) {
let res1 = await func1(l);
if (res1 == undefined) {
return /*appropriate value*/;
}
let res2 = await func2(res1);
if (res2 == undefined) {
return /*appropriate value*/;
}
if (res2 > 5) {
// ... and so on
}
}
然后我将使用 Promise.all
和 map
来启动所有这些并让它们并行运行,以数组形式获取结果(如果您需要结果):
function myFunc() {
return Promise.all(myList.map(doOne)); // Assumes `doOne` is written expecting to be called via `map` (e.g., won't try to use the other arguments `map` gives it)
// return Promise.all(myList.map(l => doOne(l))); // If we shouldn't make that assumption
}
如果 myList
是(或可能)非数组可迭代对象,请使用 Array.from
获取要使用的数组 map
:
function myFunc() {
return Promise.all(Array.from(myList.map(doOne)));
}
(或者使用 for-of
循环推送到数组。)
如果您不希望处理列表中的一个条目失败,从而阻止查看处理列表中其他条目的结果,请使用 Promise.allSettled
而不是 Promise.all
。 (请注意,它们都会以任何一种方式启动,唯一的区别是当其中至少一个失败时您是否会看到成功的结果。)
关于javascript - 使用 async/await Promise 在 "parallel"中运行 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66868195/