Created
September 6, 2019 10:29
-
-
Save johnathanesanders/52959fc05124953754f23d7a8ce9b5a2 to your computer and use it in GitHub Desktop.
An Asynchronous for-each for JavaScript and Typescript
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
/** | |
* | |
* Asyncronously iterate over an array | |
* @example | |
* var array = [1,2,3]; | |
* console.log(`This is just the beginning!`); | |
* await asyncForEach(array, function (element) { | |
* console.log(`Iterating ${element}`); | |
* }); | |
* console.log(`Done!`); | |
* @param {Array.<any>} input - The input array in which to iterate over. | |
* @param {any} next - The callback function to execute on each array element. | |
* @returns {Promise<void>} Thenable/Awaitable void return | |
*/ | |
async function asyncForEach(input, next) { | |
for (var i = 0;i < input.length;i++) { | |
await next(input[i], i, input); | |
} | |
} |
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
/** | |
* | |
* Asyncronously iterate over an array | |
* @example | |
* const array: number[] = [1,2,3]; | |
* console.log(`This is just the beginning!`); | |
* await asyncForEach(array, (element: number) => { | |
* console.log(`Iterating ${element}`); | |
* }); | |
* console.log(`Done!`); | |
* @param {Array.<any>} input - The input array in which to iterate over. | |
* @param {any} next - The callback function to execute on each array element. | |
* @returns {Promise<void>} Thenable/Awaitable void return | |
*/ | |
const asyncForEach = async (input: any[], next: any): Promise<void> => { | |
for (let i = 0;i < input.length;i++) { | |
await next(input[i], i, input); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A very handy asynchronous for-each iterator for Typescript and JavaScript.
Shamelessly adopted from Sebastien Chopin's article