JBone JBone - 2 months ago 14
Node.js Question

Nodejs async.series not executing all the methods

I am trying to use 'async' for my work, so I have written a sample program to make sure that works. async.parallel() works as expected, but not the async.series(). Not sure what I am missing. Can anyone take a look at this sample code and point out the problem/mistake?

async.series([task1, task2]) is just executing 'task1' ONLY.

const async = require('async');
var firstThing = function() {
setTimeout(function(){console.log('IN the First thing')}, 1000);
};

var secondThing = function () {
setTimeout(function(){console.log('IN the second thing')}, 1500);
};

async.series(
[
firstThing,
secondThing
],
function (err, result) {
console.log('blah blah '+result);
});


when I run this code, I get

IN the First thing


and exits. Why is the second task not being called? what am I missing?

Thanks.

Answer

You have to call back when you finish each of the functions you want to run in series:

const async = require('async');
var firstThing = function(callback) {
  setTimeout(function(){console.log('IN the First thing')}, 1000);
  callback(/* pass error or callback*/);
};

var secondThing = function (callback) {
  setTimeout(function(){console.log('IN the second thing')}, 1500); 
  callback(/* pass error or callback*/);
};