Skip to content

Commit 7094a8d

Browse files
committed
Create Promise Sequence Piping js file
- MDN example to play with demonstrating using Array.prototype.reduce on a sequence of Promises
1 parent be7c301 commit 7094a8d

1 file changed

Lines changed: 20 additions & 0 deletions

File tree

promSeqPipe.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/* Promise sequencing is essentially function piping demonstrated in the previous section, except done asynchronously.
2+
*/
3+
4+
// Compare this with pipe: fn(acc) is changed to acc.then(fn),
5+
// and initialValue is ensured to be a promise
6+
const asyncPipe =
7+
(...functions) =>
8+
(initialValue) =>
9+
functions.reduce((acc, fn) => acc.then(fn), Promise.resolve(initialValue));
10+
11+
// Building blocks to use for composition
12+
const p1 = async (a) => a * 5;
13+
const p2 = async (a) => a * 2;
14+
// The composed functions can also return non-promises, because the values are
15+
// all eventually wrapped in promises
16+
const f3 = (a) => a * 3;
17+
const p4 = async (a) => a * 4;
18+
19+
asyncPipe(p1, p2, f3, p4)(10).then(console.log); // 1200
20+

0 commit comments

Comments
 (0)