Skip to content

Instantly share code, notes, and snippets.

@johnathanesanders
Created September 6, 2019 10:29
Show Gist options
  • Save johnathanesanders/52959fc05124953754f23d7a8ce9b5a2 to your computer and use it in GitHub Desktop.
Save johnathanesanders/52959fc05124953754f23d7a8ce9b5a2 to your computer and use it in GitHub Desktop.
An Asynchronous for-each for JavaScript and Typescript
/**
*
* 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);
}
}
/**
*
* 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);
}
}
@johnathanesanders
Copy link
Author

A very handy asynchronous for-each iterator for Typescript and JavaScript.

Shamelessly adopted from Sebastien Chopin's article

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment