Skip to content

Instantly share code, notes, and snippets.

@ungarson
Created July 20, 2019 06:09
Show Gist options
  • Save ungarson/4ec741ec34b44a2ab017a64e6a4bd53e to your computer and use it in GitHub Desktop.
Save ungarson/4ec741ec34b44a2ab017a64e6a4bd53e to your computer and use it in GitHub Desktop.
Composition of asynchronous functions in javascript
export default function compose(...fns) {
return async x => {
let res = x;
for (const fn of fns) {
res = await fn(res);
}
return res;
}
}
// Example of usage
// const f1 = x => {
// return new Promise((resolve, reject) => {
// setTimeout(() => {
// resolve(x * 2);
// }, 500);
// });
// }
// const f2 = x => {
// return new Promise((resolve, reject) => {
// setTimeout(() => {
// resolve(x + 3);
// }, 100);
// });
// }
// (async () => {
// const f = compose(f1, f2);
// const value = await f(7); // ((7 * 2) + 3)
// console.log(value); // 17
// })();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment