How to make array.forEach(asyncfn) synchronized?

后端 未结 4 2031
渐次进展
渐次进展 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 06:43

    I've been using this function for a while, in case if a dedicated library is not desired:

    // usage: 
    
    // array.asyncEach(function(item, resume) {
    //   do something...
    //   console.log(item); 
    //   resume(); // call `resume()` to resume the cycle
    // }
    //
    // unless resume() is called, loop doesn't proceed to the next item
    
    Array.prototype.asyncEach = function(iterator) {
      var list    = this,
          n       = list.length,
          i       = -1,
          calls   = 0,
          looping = false;
    
      var iterate = function() {
        calls -= 1;
        i += 1;
        if (i === n) return;
        iterator(list[i], resume);
      };
    
      var loop = function() {
        if (looping) return;
        looping = true;
        while (calls > 0) iterate();
        looping = false;
      };
    
      var resume = function() {
        calls += 1;
        if (typeof setTimeout === 'undefined') loop();
        else setTimeout(iterate, 1);
      };
      resume();
    };

    Perform any async tasks inside the function, and call resume() when you are done.

    I don't remember where did I get this function from.

提交回复
热议问题