首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Superagent在异步瀑布中移动响应回调位置

Superagent在异步瀑布中移动响应回调位置
EN

Stack Overflow用户
提问于 2014-05-03 06:05:14
回答 2查看 2.2K关注 0票数 1

我有一个简单的superagent/async瀑布请求,如下所示:

代码语言:javascript
运行
复制
  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

如果我用额外的步骤执行完全相同的事情:

代码语言:javascript
运行
复制
  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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-05-13 00:40:33

在他们选择如何处理作为回调传递的函数方面,这是一个SuperAgent“问题”。如果该函数期望的是长度特性报告的两个参数,那么“传统”errres就会像异步一样给出。如果传递的函数没有将其长度报告为2,那么第一个参数是res。这是超级代理处理回调的源

代码语言:javascript
运行
复制
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,这样您就可以得到传递给回调的任何错误。

代码语言:javascript
运行
复制
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
票数 1
EN

Stack Overflow用户

发布于 2014-05-03 09:12:42

异步瀑布将错误直接传递给它的回调。数组中的第二个函数只接收一个参数-- res。数组中的每个函数都应该有自己的回调作为最后一个参数。如果错误发生,你应该在瀑布的回调中捕捉到。尝试:

代码语言:javascript
运行
复制
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); 
 });
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23440922

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档