3

I want to call two functions and get the results in parallel but one of the function's results needed to be adapted. So the function structure is:

function test(cb) {
async.parallel({
    func1: function foo(cb1) {
        cb(null, {});
    },
    func2: function bar(cb2) {
        async.waterfall([
            function adapt1(next) {
                //do something;
            },
            function adapt2(next) {
                //do something;
            }
        ], function handler(err, res) {
            //do something.
        })
    }
}, function handler2(err, res) {
    cb(null, {});
})

}

However, it just seems hang there forever. not sure if I can use async in this way....

JudyJiang
  • 2,207
  • 6
  • 27
  • 47

1 Answers1

3

Sure you can! You have to be sure to call your callbacks in the correct order and in the first place. For example, func1 should be calling cb1 not cb. Secondly, your waterfall is not invoking their callbacks at all. Take this code for example.

'use strict';

let async = require('async');

function test(callback) {
  async.parallel({
    func1: function(cb) {
      cb(null, { foo: 'bar' });
    },
    func2: function(cb) {
      async.waterfall([
        function(cb2) {
          cb2(null, 'a');
        },
        function(prev, cb2) {
          cb2(null, 'b');
        }
      ], function(err, result) {
        cb(err, result);
      });
    }
  }, function(err, results) {
    callback(err, results);
  });
}

test(function(err, result) {
  console.log('callback:', err, result);
});

Outputs: callback: null { func1: { foo: 'bar' }, func2: 'b' }

Joe Haddad
  • 1,688
  • 12
  • 11