我可以在 async.parallel 中使用 async.waterfall 吗?

can I use async.waterfall inside async.parallel?

本文关键字:async waterfall parallel 我可以      更新时间:2023-09-26

我想调用两个函数并并行获取结果,但其中一个函数的结果需要调整。所以函数结构是:

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, {});
})

}

然而,它似乎永远挂在那里。 不确定我是否可以以这种方式使用异步....

当然可以!您必须确保首先以正确的顺序调用回调。例如,func1 应该调用cb1而不是cb 。其次,您的瀑布根本不调用他们的回调。以这段代码为例。

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

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