Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Last active June 15, 2023 12:54
Show Gist options
  • Save CMCDragonkai/4b6ea09fc193b76bf80451da303ee1dc to your computer and use it in GitHub Desktop.
Save CMCDragonkai/4b6ea09fc193b76bf80451da303ee1dc to your computer and use it in GitHub Desktop.
Sequentially map an action (function that returns a promise) to an array of items #javascript
// I've deliberately named this `forP_` becaus it matches Haskell's `forP_` too
function forP_<T, P extends PromiseLike<void> = Promise<void>>(
items: readonly T[],
f: (item: T) => PromiseLike<void>,
seed?: P
): P {
return items.reduce((pChain, item) => {
return pChain.then(() => f(item));
}, seed ?? Promise.resolve()) as P;
}
@CMCDragonkai
Copy link
Author

CMCDragonkai commented Jun 5, 2023

Basically this is the equivalent of doing:

for (const x of somearr) {
  await f(x);
}

But without using async await syntax.

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