Skip to content

Instantly share code, notes, and snippets.

@neharkarvishal
Last active December 24, 2019 18:23
Show Gist options
  • Save neharkarvishal/dc9922606a0a5be759fa51a9330af27b to your computer and use it in GitHub Desktop.
Save neharkarvishal/dc9922606a0a5be759fa51a9330af27b to your computer and use it in GitHub Desktop.
/**
* 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)
})();
@neharkarvishal
Copy link
Author

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.

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