Posts tagged "es8"

How to chain multiple functions in Javascript properly with async/await

The code below chains multiple functions waits for everything to resolve, and then sends the result:

// chain any number of async functions
const asyncChain = (...fns) => x => fns.reduce(async (res, fn) => fn(await res), x);

// async functions
const add = async x => x + 1;
const multiply = async x => x * 2;
const square = async x => x * x;

const getResult = asyncChain(add, multiply, square);

(async () => console.log(await getResult(4)))(); // 100