Skip to content

Instantly share code, notes, and snippets.

@xwlee
Created June 7, 2023 04:36
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 xwlee/bb92501acaf75aabfee399d3d266e6d5 to your computer and use it in GitHub Desktop.
Save xwlee/bb92501acaf75aabfee399d3d266e6d5 to your computer and use it in GitHub Desktop.
forEachAsync.ts
const forEachAsync = <T>(arr: T[], fn: (x: T) => any): Promise<any> =>
arr.reduce(
(promise: Promise<void>, value: T) => promise.then(() => fn(value)),
Promise.resolve()
);
(async () => {
console.log("START FOREACH VIA REDUCE");
await forEachAsync([1, 2, 3, 4], async (n) => {
const x = await fakeAPI(n * 1000, n);
useResult(x);
});
console.log("END FOREACH VIA REDUCE");
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment