Created
July 20, 2019 06:09
-
-
Save ungarson/4ec741ec34b44a2ab017a64e6a4bd53e to your computer and use it in GitHub Desktop.
Composition of asynchronous functions in javascript
This file contains hidden or 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
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