Superagent在asynchronous瀑布中移动响应callback位置

我有一个简单的工作superagent / async瀑布请求,看起来像这样:

  request = require 'superagent' user = request.agent() async.waterfall [ (cb)-> user.post('http://localhost:3000/form').send(name: 'Bob').end(cb) ], (err, res)-> console.log err console.log res 

这成功地打印我的完整http响应,而errundefined

如果我用一个额外的步骤完成同样的事情:

  request = require 'superagent' user = request.agent() async.waterfall [ (cb)-> user.post('http://localhost:3000/form').send(name: 'Bob').end(cb) (err, res)-> # this is never reached cb() ], (err, res)-> console.log err # this now prints out the response console.log res # this is undefined 

err现在是回应。 res是不确定的。 这是我遇到的一个superagent问题,还是我错误地使用asyncwaterfall

SuperAgent的“问题”在于如何select处理作为callback传递的函数。 如果该函数正好期待length属性报告的两个参数,那么“传统” errres就像Async所愿。 如果你传递的函数没有报告它的长度是2,那么给出的第一个参数是res 。 以下是SuperAgent处理callback的来源 :

 Request.prototype.callback = function(err, res){ var fn = this._callback; if (2 == fn.length) return fn(err, res); if (err) return this.emit('error', err); fn(res); }; 

为了保证你的callback是按照预期的方式调用的,我会build议传递一个匿名函数来end这样它就可以将它的长度报告为两个,这样你就可以得到任何传递给你callback的错误。

 request = require 'superagent' user = request.agent() async.waterfall [ (cb) -> user.post('http://localhost:3000/form').send(name: 'Bob').end (err, res) -> cb err, res (err, res) -> # err should be undefined if the request is successful # res should be the response cb null, res ], (err, res) -> console.log err # this should now be null console.log res # this should now be the response 

asynchronous瀑布直接将错误传递给它的callback。 数组中的第二个函数只接收一个参数 – res 。 数组中的每个函数都应该有自己的callback作为最后一个参数。 如果发生错误,你应该抓住瀑布的callback。 尝试:

 async.waterfall([ function(cb){ superagent...end(cb); }, function(res, cb){ //Note cb here. //If you don't pass res here, waterfall's callback will not receive it cb(null, res); }], function(err, res){ //If superagent fails you should catch err here should.not.exist(err); //res is defined because you passed it to callback of the second function should.exist(res); });