Skip to content

Instantly share code, notes, and snippets.

@ajmas
Created May 4, 2020 17:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajmas/831d9e447e1c3da0104799189ef7e9a7 to your computer and use it in GitHub Desktop.
Save ajmas/831d9e447e1c3da0104799189ef7e9a7 to your computer and use it in GitHub Desktop.
Async Array functions in NodeJS
/**
* This module provides a set of async friendly functions that
* mirror the non-async versions in array.
*
* They are not necessarily optimised, but they do work when we
* need to deal with async or promise based operations in the
* handler.
*/
/**
* This is equivalent to Array.map, but with support for
* async functions.
*
* @param array
* @param handler
*/
async function map (array: Array<any>, handler: Function) {
const newArray = [];
for (let i = 0; i < array.length; i++) {
newArray[i] = await handler(array[i]);
}
return newArray;
}
/**
* This is equivalent to Array.forEach, but with support for
* async functions.
*
* @param array
* @param handler
*/
async function forEach (array: Array<any>, handler: Function) {
const newArray = [];
for (let i = 0; i < array.length; i++) {
newArray[i] = await handler(array[i]);
}
return newArray;
}
export default { map, forEach };
export {
map as asyncMap,
forEach as asyncForEach
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment