使用异步瀑布传递参数

时间:2017-04-27 14:19:37

标签: node.js async.js

考虑这样一种情况,其中瀑布中第一个函数的回调值需要在后续函数中多次使用,以最终合并结果。在下面的代码中,baseFn应该在回调中返回一个数组,然后应该逐个元素地处理该数组,如subFn1和subFn2所示。此后,必须将subFn1和subFn2的返回回调附加到新数组中以生成最终结果。我试图看看,如果有一种方法可以使用async.series和async.apply来实现这一点,但无法进一步发展。请指教。

async.waterfall ([  

  function baseFn(baseCb) {      
    //a method that gets an array of elements  
    return (null, elementArray);
  },  
  function subFn1(elemArr, subFnCb) {  
    var elem = elemArr[0];  
    //a method that returns processed element  
    return (null, proc_elem1);  
  },  
  function subFn2(elemArr,subFnCb) {  
    var elem = elemArr[1];
    //a method that returns processed element  
    return (null, proc_elem2);  
  },  
  function aggOut() {}  
], function getOutput (err, out) {  
      console.log(out);  
})

2 个答案:

答案 0 :(得分:2)

由于subFn1()和subFn2()都依赖于baseFn,因此最好使用async.auto(),因为我们可以指定subFn1和subFn2的依赖关系是baseFn()。这是代码:

var async = require('async');

async.auto({
  baseFn: function(autoCb) {
    var elementArray = ['one', 'two'];
    autoCb(null, elementArray);
  },
  subFn1: ['baseFn', function(results, autoCb) {
    var elem = results.baseFn[0];
    console.log('subFn1', elem);

    var proc_elem1 = 'proc_elem1';
    autoCb(null, proc_elem1);
  }],
  subFn2: ['baseFn', function(results, autoCb) {
    var elem = results.baseFn[1];
    console.log('subFn2', elem);

    var proc_elem2 = 'proc_elem2';
    autoCb(null, proc_elem2);
  }]
}, function(err, results) {
  console.log('results', results);
});

输出看起来像这样(注意subFn1和subFn2完成的顺序并不保证,因为它们并行运行。但是,最终回调中的最终'results'对象将具有所有结果):

subFn1 one
subFn2 two
results { baseFn: [ 'one', 'two' ],
  subFn1: 'proc_elem1',
  subFn2: 'proc_elem2' }

答案 1 :(得分:1)

const baseFn = function(baseCb) {
  // ...
  return baseCb(elementArray);
}

baseFn(function(elemArr) {
  // since subFn1 and subFn2 both need elemArr independently,
  // lets use async.parallel here.
  async.parallel([
    function subFn1(elemArr, subFnCb) {
      // ...
      return subFnCb(null, proc_elem1);
    }),
    function subFn2(elemArr, subFnCb) {
      // ...
      return subFnCb(null, proc_elem2);
    }),
  ], function(err, result) {
    // async.parallel callback with proc_elem1 and 2 in result.
    // you can now create your final result with elementArray
    // and both proc_elem.
    console.log([elemArr, result[0], result[1]]);
  });
});