Skip to content

Instantly share code, notes, and snippets.

@jperasmus
Last active June 30, 2022 07:48
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save jperasmus/fbbcccb387896ff7db2c58797ebb76da to your computer and use it in GitHub Desktop.
Save jperasmus/fbbcccb387896ff7db2c58797ebb76da to your computer and use it in GitHub Desktop.
"compose" function that handles both sync and async functions
// Async compose
const compose = (…functions) => input => functions.reduceRight((chain, func) => chain.then(func), Promise.resolve(input));
// Functions fn1, fn2, fn3 can be standard synchronous functions or return a Promise
compose(fn3, fn2, fn1)(input).then(result => console.log(`Do with the ${result} as you please`))
@mk0y
Copy link

mk0y commented Mar 14, 2020

This works great. 👍

@jperasmus
Copy link
Author

Awesome, I'm glad it is useful to you too. 🤗

@obanoff
Copy link

obanoff commented Jan 29, 2022

great, very useful
could add catch if it's necessary:
const compose = (…functions) => input => functions.reduceRight((chain, func) => chain.then(func), Promise.resolve(input)).catch(err => console.warn(err));

@EvgenyArtemov
Copy link

Great!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment