Created
August 25, 2017 15:23
-
-
Save dalaidunc/14b9110cff8df876d6cdf4815774f706 to your computer and use it in GitHub Desktop.
Creating an async version of forEach on Array.prototype
This file contains hidden or 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
// 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