Created
May 4, 2020 17:13
-
-
Save ajmas/831d9e447e1c3da0104799189ef7e9a7 to your computer and use it in GitHub Desktop.
Async Array functions in NodeJS
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
/** | |
* 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