How to make array.forEach(asyncfn) synchronized?

后端 未结 4 2036
渐次进展
渐次进展 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条回答
  •  萌比男神i
    2021-01-27 06:56

    I have used a library called async. There a function called eachSeries. It takes an array, an async function, and a callback. The function is called on each item for the array.

    This question can open a rabbit hole of complexity. You will need to be careful that your async function doesn't make an asynchronous call. The library provides a callback that can be useful in this case.

    function asyncFunction(val, callback) {
    
       return (function() {
         //do stuff
    
         callback();
       })();
    }
    

    The callback will initiate the a call on the next item in the array.

提交回复
热议问题