我有一个简单的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响应,err
是undefined
。
如果我用额外的步骤执行完全相同的事情:
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
问题,还是我简单地错误地使用了async
的waterfall
?
发布于 2014-05-13 00:40:33
在他们选择如何处理作为回调传递的函数方面,这是一个SuperAgent“问题”。如果该函数期望的是长度特性报告的两个参数,那么“传统”err
和res
就会像异步一样给出。如果传递的函数没有将其长度报告为2,那么第一个参数是res
。这是超级代理处理回调的源
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);
};
为了保证您的回调按预期的方式调用,我建议将一个匿名函数传递给end
,这样它肯定会将其长度报告为2,这样您就可以得到传递给回调的任何错误。
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
发布于 2014-05-03 09:12:42
异步瀑布将错误直接传递给它的回调。数组中的第二个函数只接收一个参数-- res
。数组中的每个函数都应该有自己的回调作为最后一个参数。如果错误发生,你应该在瀑布的回调中捕捉到。尝试:
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);
});
https://stackoverflow.com/questions/23440922
复制相似问题