2013-12-23 30 views
0

我收到一个我不明白的错误。我使用一组函数调用async.waterfall。为了清楚起见,该功能被“缩短”。使用具有参数的回调数组的节点异步瀑布

FabricCommand.prototype.do = function (callback, undoArray) { 
    var self = this; 

    if (undoArray === undefined) { 
     undoArray = []; 
    } 

    undoArray.push(self); 
    callback(null, undoArray); 
}; 

我创建阵列如下面所列:doCommands是一个阵列和所述对象被原样添加:

doCommands.push(fabricCommand.do.bind(fabricCommand)); 

瀑布设置:

async.waterfall(
    doCommands, 
    function(err, undoCommands){ 
     if (err) { 
      // do something ... 
     } 
     else { 
      console.log('we succeeded with all the do commands... and there are ' 
       + undoCommands.length 
       + ' in the undoCommands but we will disregard it...'); 
     } 
    } 
); 

现在,当运行此代码,第一次通过FabricCommand.do函数,我分配了undoCommands数组并添加了一个,下次通过我得到,我尝试添加数组元素,出现以下错误:

undoArray.push(something); 
     ^TypeError: Object function (err) { 
      if (err) { 
       callback.apply(null, arguments); 
       callback = function() {}; 
      } 
      else { 
       var args = Array.prototype.slice.call(arguments, 1); 
       var next = iterator.next(); 
       if (next) { 
        args.push(wrapIterator(next)); 
       } 
       else { 
        args.push(callback); 
       } 
       async.setImmediate(function() { 
        iterator.apply(null, args); 
       }); 
      } 
     } has no method 'push' 

任何人都可以看到我做错了什么?

回答

1

async.waterfall执行必须具有以下签名的功能:

function(arg, callback) { … } 

,或者使用多个参数:

function(arg1, arg2, callback) { … } 

在你的情况,你干脆倒了两个参数:

FabricCommand.prototype.do = function (callback, undoArray) { … } 

callback收到预期值存储在undoArray中,而undoArray收到了用于callback的值,即函数:这就是为什么你遇到了这个奇怪的错误(function […] has no method 'push')。

你需要把这些参数正确的顺序:

FabricCommand.prototype.do = function (undoArray, callback) { … } 

的第二个问题是,瀑布的第一函数只接收一个参数:回调(因为没有要接收的值,因为它是瀑布的第一个功能)。一个解决方案是检查参数的数量:

if (Array.prototype.slice.apply(arguments).length === 1) { 
    callback = undoArray; 
    undoArray = undefined; 
} 

这是working gist

+0

谢谢,我仍然保持回调(null,undoArray);原样或调用必须颠倒参数? – reza

+0

是的,这是[标准Node.js回调风格](http://nodeguide.com/style.html)。第一个参数是错误(不是空,'async'会停止瀑布并立即调用最后一次回调),第二个参数是结果,它将被传递给瀑布中的下一个函数。 –

+0

让我再试试这个,我想我试过并且没有工作 – reza