Last active
December 24, 2019 18:23
-
-
Save neharkarvishal/dc9922606a0a5be759fa51a9330af27b to your computer and use it in GitHub Desktop.
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
/** | |
* pipeAsyncFunctions.js | |
* tags: { JavaScript, Adapter, Function, Promise } | |
* Performs left-to-right function composition for asynchronous functions. | |
* Use Array.prototype.reduce() with the spread operator (...) to perform | |
* left-to-right function composition using Promise.then(). The functions can | |
* return a combination of: simple values, Promise's, or they can be defined as | |
* async ones returning through await. All functions must be unary. | |
*/ | |
const pipeAsyncFunctions = (...fns) => args => | |
fns.reduce((p, f) => p.then(f), Promise.resolve(args)); | |
const sum = pipeAsyncFunctions( | |
x => x + 1, | |
x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)), | |
x => x + 3, | |
async x => (await x) + 4 | |
); | |
(async () => { | |
console.log(await sum(5)); // 15 (after one second) | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
pipeAsyncFunctions.js
tags: { JavaScript, Adapter, Function, Promise }
Performs left-to-right function composition for asynchronous functions.
Use
Array.prototype.reduce()
with the spread operator (...
) to performleft-to-right function composition using
Promise.then()
. The functions canreturn a combination of: simple values,
Promise
's, or they can be defined asasync ones returning through
await
. All functions must be unary.