Files
30-seconds-of-code/snippets/chainAsync.md
Angelos Chalaris 8a6b73bd0c Update covers
2023-02-16 22:24:28 +02:00

720 B

title, tags, cover, firstSeen, lastUpdated
title tags cover firstSeen lastUpdated
Chain async functions function tram-car 2017-12-17T17:55:51+02:00 2020-09-15T16:28:04+03:00

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');
  }
]);