Skip to content

Instantly share code, notes, and snippets.

@rpgeeganage
Created November 1, 2018 22:20
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 rpgeeganage/4887a8bbd2494d2d5809449442792691 to your computer and use it in GitHub Desktop.
Save rpgeeganage/4887a8bbd2494d2d5809449442792691 to your computer and use it in GitHub Desktop.
ForEach method
// Signature of the callback
type CallBackForEach<T> = (
value: T,
index?: number,
collection?: T[]
) => Promise<void>;
/**
* Async ForEach function
*
* @export
* @template T
* @param {T[]} elements
* @param {CallBackForEach<T>} cb
* @returns {Promise<void>}
*/
async function aForEach<T>( elements: T[], cb: CallBackForEach<T> ): Promise<void> {
for (const [index, element] of elements.entries()) {
await cb(element, index, elements);
}
}
// You can use as follows
const array = [1, 2, 3, 4];
const output: number[] = [];
await aForEach<number>(array, async (i) => {
output.push(i);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment