How to make array.forEach(asyncfn) synchronized?

后端 未结 4 2037
渐次进展
渐次进展 2021-01-27 06:17

Say I have an array and I want to perform an async-function on each element of the array.

let a = [x1, x2, x3]

// I want to
await a.forEach(async (x) => {...         


        
4条回答
  •  心在旅途
    2021-01-27 07:04

    Like this?

    for (let x of a) {
      await fn(x);
    }
    

    Or if you really dislike creating a separate fn:

    for (let x of a) {
      await (async v => {
        ...
      })(x);
    }
    

    You could even add it to Array.prototype:

    Array.prototype.resolveSeries = async function(fn) {
      for (let x of this) {
        await fn(x);
      }
    }
    
    // Usage:
    await a.resolveSeries(fn);
    
    // Or:
    await a.resolveSeries(async x => {
      ...
    });
    

提交回复
热议问题