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) => {...
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.