Iva*_*van 2 javascript promise async-await typescript
我目前有一个这样的 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
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是 func1、func2 是返回承诺的网络调用,我不希望它们在等待它们时阻塞我的 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
}
}
Run Code Online (Sandbox Code Playgroud)
然后我将使用Promise.allwithmap启动所有这些并让它们并行运行,以数组形式获取结果(如果您需要结果):
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
}
Run Code Online (Sandbox Code Playgroud)
如果myList是(或可能是)非数组可迭代,则使用Array.from来获取要使用的数组map:
function myFunc() {
return Promise.all(Array.from(myList.map(doOne)));
}
Run Code Online (Sandbox Code Playgroud)
(或者使用for-of循环推送到数组。)
如果您不希望处理列表中的一项失败而无法看到处理列表中其他项的结果,请使用Promise.allSettled而不是Promise.all。(请注意,它们都会以任何一种方式启动,唯一的区别是当其中至少一个失败时您是否会看到成功的结果。)
| 归档时间: |
|
| 查看次数: |
2367 次 |
| 最近记录: |