Recursive Implementation for Asyn.series

We are going to look into a recursive solution for the series method. Note that recursive always comes with a performance dent with a deeper call stack of instruction execution in the hardware.

The idea here will start with a function1 from the tasks array and then pass a wrapped callback function on reading the result of function1, then invoking function2 and vice versa. If any error occurs in the process, the algorithom will exit by calling the final callback with error and results collection.

    fn((error, result) => {
      if (error) {
        callback(error, results);
        return;
      }
      results.push(result);
      //invoke a recursive call to next method 
    });

The full code is available in the below code block and it is ready to execute in your console for analysis or debug to see how this works in action.

const sampleTasks =  [ function (callback) { setTimeout(function () { console.log("1"); callback(null, "one"); }, 200); }, function (callback) { setTimeout(function () { console.log("2"); callback(null, "two"); }, 100); }, function (callback) { setTimeout(function () { console.log("3"); callback(null, "three"); }, 90); }, function (callback) { setTimeout(function () { console.log("4"); callback(Error("some error")); }, 10); }, function (callback) { setTimeout(function () { console.log("5"); callback(null, "five"); }, 1000); }, ];
 
function onSeriesCompleted(error, results) {
  console.log("Error stack", error);
  console.log("Results of successfully executed tasks", results);
}

function startTask(tasks, callback, counter = 0, results = []) {
  if (counter < tasks.length) {
    const fn = tasks[counter];
    const fn2 = tasks[counter + 1];
    fn((error, result) => {
      if (error) {
        callback(error, results);
        return;
      }
      results.push(result);
      startTask(tasks, callback, ++counter, results);
    });
  }
}

function series(tasks, finalCallback) {
  startTask(tasks, finalCallback);
}

series(sampleTasks, onSeriesCompleted);

Output

Leave a Reply

Your email address will not be published. Required fields are marked *