Last active
July 7, 2021 20:22
-
-
Save Josema/97547299fe544e949a6539dd98d50a86 to your computer and use it in GitHub Desktop.
forEachAsync
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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') | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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