Skip to content

Instantly share code, notes, and snippets.

@dalaidunc
Created August 25, 2017 15:23
Show Gist options
  • Save dalaidunc/14b9110cff8df876d6cdf4815774f706 to your computer and use it in GitHub Desktop.
Save dalaidunc/14b9110cff8df876d6cdf4815774f706 to your computer and use it in GitHub Desktop.
Creating an async version of forEach on Array.prototype
// extend the Array prototype with an asyncForEach method
Array.prototype.asyncForEach = async function (fn) {
for (let i = 0; i < this.length; i++) {
await fn(this[i], i);
}
};
const arr = ['a', 'b', 'c', 'd'];
// define a Promise wrapper around the setTimeout function
function wait (fn, time) {
return new Promise(resolve => setTimeout(() => {fn();resolve();}, time));
}
// call an asynchronous function upon each element in the array
arr.asyncForEach(async (item, index) => {
await wait(() => console.log(item), 500);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment