nodejs loop async.parallel callback

1.1k views Asked by At

I am testing a callback called by async.parallel functions: it seems that the execution flow is different if the callback uses a parameter or none.

var async = require("async");

function makeTestFunction(i) {
 return function(callback) {
  console.log('test Function: '+i);
  return callback();
 };
}

function test(callback) {
 var endFunctions = function(i) {
  console.log('ending: ' + i);
  return callback();
 };
 var testFunctions = [];
 for (var i=0; i < 3; i++) {
  console.log('loop: '+i);
  testFunctions.push(makeTestFunction(i));
 }
 return async.parallel(testFunctions, endFunctions );
}

test( function() {
 console.log('--------------- end test 1');
});
// loop: 0
// loop: 1
// loop: 2
// test Function: 0
// test Function: 1
// test Function: 2
// ending: null
// --------------- end test 1

The result is what I expected: 'endFunctions' callback is called after all the functions finished.

Now I want the anonymous functions callback to return a value :

var async = require("async");

function makeTestFunction(i) {
 return function(callback) {
  console.log('test Function: '+i);
  return callback(i);
 };
}

function test(callback) {
 var endFunctions = function(i) {
  console.log('ending: ' + i);
  return callback();
 };
 var testFunctions = [];
 for (var i=0; i < 3; i++) {
  console.log('loop: '+i);
  testFunctions.push(makeTestFunction(i));
 }
 return async.parallel(testFunctions, endFunctions );
}

test( function() {
 console.log('--------------- end test 2');
});
// loop: 0
// loop: 1
// loop: 2
// test Function: 0
// test Function: 1
// ending: 1
// --------------- end test 2
// test Function: 2

reading async.parralel manual, I expected:

  1. the callback 'endFunctions' to be called once after all the anonymous functions are terminated
  2. The callback 'endFunctions' to receive an array of all the values returned by anonymous functions.

Please, can somebody explain what happened and what is wrong?

1

There are 1 answers

0
Roge On

What is wrong is the callback signature. For async.parallel, the callback must have two parameters (err, results).

The following code gives the proper result:

var async = require("async");

function makeTestFunction(i) {
 console.log('make function: '+i);
 return function(callback) {
  console.log('test Function: '+i);
  return callback(null, i);
 };
}

function test(callback) {
 var endFunctions = function(err, result) {
  console.log('ending: ' + result);
  return callback();
 };
 var testFunctions = [];
 for (var i=0; i < 3; i++) {
  (function (k) {
   testFunctions.push(makeTestFunction(k));
  })(i);
 }
 return async.parallel(testFunctions, endFunctions );
}

test( function() {
 console.log('--------------- end test 2');
});
// make function: 0
// make function: 1
// make function: 2
// test Function: 0
// test Function: 1
// test Function: 2
// ending: 0,1,2
// --------------- end test 2