Node.js async.js Series : independent mono-tasking

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

async.series(tasks, afterTasksCallback) will execute a set of tasks. Each task are executed after another. If a task fails, async stops immediately the execution and jump into the main callback.

When tasks are finished successfully, async call the "master" callback with all errors and all results of tasks.

function shortTimeFunction(callback) {
  setTimeout(function() {
    callback(null, 'resultOfShortTime');
  }, 200);
}

function mediumTimeFunction(callback) {
  setTimeout(function() {
    callback(null, 'resultOfMediumTime');
  }, 500);
}

function longTimeFunction(callback) {
  setTimeout(function() {
    callback(null, 'resultOfLongTime');
  }, 1000);
}

async.series([
    mediumTimeFunction,
    shortTimeFunction,
    longTimeFunction
  ],
  function(err, results) {
    if (err) {
      return console.error(err);
    }

    console.log(results);
  });

Result : ["resultOfMediumTime", "resultOfShortTime", "resultOfLongTime"].

Call async.series() with an object

You can replace the tasks array parameter by an object. In this case, results will be also an object with the same keys than tasks.

It's very useful to compute some tasks and find easily each result.

async.series({
    short: shortTimeFunction,
    medium: mediumTimeFunction,
    long: longTimeFunction
  },
  function(err, results) {
    if (err) {
      return console.error(err);
    }

    console.log(results);
  });

Result : {short: "resultOfShortTime", medium: "resultOfMediumTime", long: "resultOfLongTime"}.



Got any Node.js Question?