Files
30-seconds-of-code/snippets/chainAsync.md
RobertAKARobin 93ab5a9e52 chainAsync update: last function shouldn't get 'next' as argument
Confident that my tests pass, but _30.js won't update.
2018-12-07 14:16:26 -06:00

578 B

chainAsync

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, last = fns[fns.length - 1];
  const next = () => {
    const fn = fns[curr++]
    fn(fn === last ? null : next)
  }
  next();
};
chainAsync([
  next => {
    console.log('0 seconds');
    setTimeout(next, 1000);
  },
  next => {
    console.log('1 second');
    setTimeout(next, 1000);
  },
  () => {
    console.log('2 second');
  }
]);