Pipe async functions

JavaScript, Function, Promise · Oct 22, 2020

Performs left-to-right function composition for asynchronous functions.

const pipeAsyncFunctions = (...fns) =>
  arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg));
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)
})();

More like this

  • Pipe functions

    Performs left-to-right function composition.

    JavaScript, Function · Oct 22, 2020

  • Reverse compose functions

    Performs left-to-right function composition.

    JavaScript, Function · Oct 22, 2020

  • Asynchronous JavaScript Cheat Sheet

    Learn everything you need to know about promises and asynchronous JavaScript with this handy cheatsheet.

    JavaScript, Function · Jun 12, 2021