Skip to content

Instantly share code, notes, and snippets.

@Josema
Last active July 7, 2021 20:22
Show Gist options
  • Save Josema/97547299fe544e949a6539dd98d50a86 to your computer and use it in GitHub Desktop.
Save Josema/97547299fe544e949a6539dd98d50a86 to your computer and use it in GitHub Desktop.
forEachAsync
// https://2ality.com/2016/10/asynchronous-iteration.html
async function forEach(object, callback) {
if (Array.isArray(object)) {
for (let prop = 0; prop < object.length; ++prop) {
await callback(object[prop], prop)
}
} else {
for (const prop in object) {
await callback(object[prop], prop)
}
}
}
// Usage:
await forEach(['A','B','C','D'], async (item, index) => {
await fetch('/whatever')
})
await forEach({A:1, B:2}, async (value, prop) => {
await fetch('/whatever')
})
function forEachAsync( arr, b, c ) {
var onNext = b;
var onFinish = c;
if ( typeof arr != 'object' ) {
onFinish = b;
onNext = arr;
arr = this;
}
var length = arr.length;
(function loop(index) {
if ( index < length )
onNext( loop.bind(this, index+1), arr[index], index );
else if ( onFinish )
onFinish();
})(0);
}
Array.prototype.forEachAsync = forEachAsync;
// USING
forEachAsync(['A','B','C','D'], (next, item, index) => {
console.log(item, index);
next();
}, () => {
console.log('END');
});
// USING AS PROTOTYPE
['E','F','G','H'].forEachAsync((next, item, index) => {
console.log(item, index);
next();
}, () => {
console.log('END');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment