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) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg)); -
const sum = pipeAsyncFunctions( +
+const sum = pipeAsyncFunctions( x => x + 1, x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)), x => x + 3, async x => (await x) + 4 ); -(async () => { +(async() => { console.log(await sum(5)); // 15 (after one second) })();
Learn new ES6 JavaScript language features like arrow function, destructuring, generators & more to write cleaner and more productive, readable programs.
Performs left-to-right function composition.
Use Array.prototype.reduce() with the spread operator (...) to perform left-to-right function composition. The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.
const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); diff --git a/docs/date.html b/docs/date.html index 3a87fe765..05dfc1a8a 100644 --- a/docs/date.html +++ b/docs/date.html @@ -156,5 +156,5 @@ t.setDate(t.getDate() + 1); return t.toISOString().split('T')[0]; }; -
tomorrow(); // 2018-10-18 (if current date is 2018-10-18) +
tomorrow(); // 2018-10-19 (if current date is 2018-10-18)