运行 for loop in "parallel" using async/await promises

Running for loop in "parallel" using async/await promises

我目前有一个这样的 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 是 return 承诺的网络调用,我不希望它们在等待它们时阻塞我的 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.allmap 来启动所有这些并让它们 运行 并行,将结果作为数组获取(如果你需要结果) :

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。 (请注意,它们都会 以任何一种方式启动 ,唯一的区别是当其中至少一个失败时您是否看到成功的结果。)