Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can I use async.waterfall inside async.parallel?

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....

like image 233
JudyJiang Avatar asked Jun 13 '26 13:06

JudyJiang


1 Answers

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' }

like image 138
Joe Haddad Avatar answered Jun 15 '26 02:06

Joe Haddad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!