This question already has answers here:
Using async/await with a forEach loop
                                
                                    (18个答案)
                                
                        
                                在4个月前关闭。
            
                    
我知道我们不能简单地做这样的事情:

myArray.forEach(async x => await asyncOperation())


编辑:我知道这是有效的,但我需要保持正确的顺序

如果必须通过异步操作遍历数组,则必须执行以下操作:

await Promise.all(myArray.map(x => asyncOperation()))


但是,我需要在同一迭代中执行两个异步操作。我知道另一种选择是只使用.reduce,它看起来像这样:

await myArray.reduce((p, el) => {
      return p.then(() => {
        return somePromise(el)
          .then(res => {
            return anotherPromise(res)
          })
      })
    }, Promise.resolve())


但是我避免嵌套承诺,而是希望仅使用async/await保留它。因此,无论如何,我的问题是,迭代需要通过两个promise的数组的最佳等待时间是什么?

最佳答案

您可以在单独的函数中执行彼此依赖的异步代码,该函数在地图中调用,然后将地图包装在Promise.all中

const doAsyncStuff = async (x) => {
    const firstValue = await fakeLongTask1();
    const finalValue = await fakeLongTask2(firstValue);
    return finalValue;
}

Promise.all(myArray.map(x => {
    doAsyncStuff(x);
}));


这将触发所有任务,但是等待彼此依赖的长任务,然后一旦完成,Promise.all就解决了。

09-17 13:22
查看更多