繁体   English   中英

使用 async/await 承诺以“并行”方式运行 for 循环

[英]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 是返回承诺的网络调用,我不希望它们在等待它们时阻塞我的 for 循环。 所以我不介意与 myList[0] 和 myList[1] 并行工作,也不关心列表项的处理顺序。

我怎样才能做到这一点?

我会通过编写一个 function 来处理您正在按顺序处理的一个值:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM