10
var async = require('async');
async.parallel([
  function(cb) {
    cb(true);
  },
  function(cb) {
    cb(null, true);
  }], 
  function(error, results) {
  }
);

In the code, if the first task runs cb(true) before the second tasks, will the second tasks still run? and If so, after it is done, will the main callback still be called?

Joe C
  • 2,757
  • 2
  • 26
  • 46

2 Answers2

11

The async.parallel executes all functions in parallel. If any of the functions pass an error to its callback (callback first parameter is not null), the main callback is immediately called with the value of the error. All functions will be executed though.

With the following code your execution will be as follows 1, 3, 2, 2.1:

var async = require('async');
async.parallel([
  function(cb) {
    console.info('1')
    cb(true);
  },
  function(cb) {
    console.info('2')
    cb(null, true);
  },
  function(cb) {
    console.info('2.1')
    cb(null, true);
  }], 
  function(error, results) {
    console.info('3')
  }
);
Tom
  • 26,212
  • 21
  • 100
  • 111
  • 2
    Is there a way to get result of all tasks even in case of error. i.e list of all errors and result in main callback. – EmptyData Jun 14 '17 at 06:51
1

yes, second task is called (because tasks are expected to be async and exit immediately). async.parallel callback is called with error from first failed task

Andrey Sidorov
  • 24,905
  • 4
  • 62
  • 75
  • 1
    Suppose there are 3 tasks t1 t2 t3, t1 t2 get errors, and t3 successes. So async.parallel's callback will be called twice for t1 and t2 individually. But after all t1, t2 and t3 are done, it does not call the callback with results. Is this correct? – Joe C Feb 03 '14 at 20:46
  • 2
    no, it'll wait for callbacks from all t1, t2, t3 (no matter success or error) and call resulting callback exactly once – Andrey Sidorov Feb 04 '14 at 01:20