Chain async functions

JavaScript, Function · Sep 15, 2020

Chains asynchronous functions.

  • Loop through an array of functions containing asynchronous events, calling next when each asynchronous event has completed.
const chainAsync = fns => {
  let curr = 0;
  const last = fns[fns.length - 1];
  const next = () => {
    const fn = fns[curr++];
    fn === last ? fn() : fn(next);
  };
  next();
};
chainAsync([
  next => {
    console.log('0 seconds');
    setTimeout(next, 1000);
  },
  next => {
    console.log('1 second');
    setTimeout(next, 1000);
  },
  () => {
    console.log('2 second');
  }
]);

More like this

  • Pipe async functions

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

    JavaScript, Function · Oct 22, 2020

  • Promisify function

    Converts an asynchronous function to return a promise.

    JavaScript, Function · Oct 22, 2020

  • Delay async function execution

    Delays the execution of an asynchronous function.

    JavaScript, Function · Oct 22, 2020