JavaScript chaining functions using promise

In this article we are going to use promise to chain functions (they execute in chain one after the other using previous values).

Here is the code:

// an attempt to chain functions

const serial=arr=>arr.reduce((acc,f)=>acc.then(f) ,Promise.resolve(10))

const f1=a=>a*2
const f2=a=>a*3
const f3=a=>a*4

serial([f1,f2,f3]).then(console.log)

When defining serial we pass to it an array of functions we are going to chain run. Then we are going to reduce them using reduce.

We first start with a promise resolved to value 10. Then we do which is like doing Promise.resolve(10).then(f1). Then it's Promise.resolve(10).then(f1).then(f2). And so on until we arrive at Promise.resolve(10).then(f1).then(f2).then(f3) in which case reduce operation ends (because we've traversed every function).

What has occurred is this arithmetic operation: 10x2x3x4=240.

Neat, huh? :)