Search code examples
javascriptcallbacksequential

How to call javascript array of methods having callbacks to run sequentially?


I have the following methods to be called sequentially.
Note that timeout is differing so by default it will run based on timeout.

function asyncTask1(done) {
  setTimeout(() => {
    console.log('task 1 done');
    done(1);
  }, 500);
}
function asyncTask2(done) {
  setTimeout(() => {
    console.log('task 2 done');
    done(2);
  }, 400);
}
function asyncTask3(done) {
  setTimeout(() => {
    console.log('task 3 done');
    done(3);
  }, 300);
}

function sequential(tasks = []) {

}
 sequential(tasks);

Solution

  • You can do it recursively:

    function sequential([first, ...last], done) {
      if (!first) done();
      else first(() => sequential(last, done);
    }