1

次のような単純な作業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私がここで遭遇している問題ですか、それとも単純にasync'sをwaterfall間違って使用していますか?

4

2 に答える 2

1

これは、コールバックとして渡される関数をどのように処理するかという SuperAgent の「問題」です。その関数が長さプロパティによって報告される正確に 2 つの引数を期待している場合、「伝統的な」errresは Async が望むように与えられます。渡した関数がその長さを 2 と報告しない場合、指定された最初の引数はresです。コールバックを処理するためのSuperAgent のソースは次のとおりです。

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-13T00:40:33.343 に答える
1

非同期ウォーターフォールは、エラーをそのコールバックに直接渡します。array の 2 番目の関数は、引数を 1 つだけ受け取ります - 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); 
 });
于 2014-05-03T09:12:42.140 に答える