1

我想在 koa 控制器中传递一个请求,它的工作:

var s = require('through2')();
var req = http.request(url, function(res) {
  res.pipe(s);
})
req.end(null);

s.on('close', function() {
  console.log('has close');
});
this.body = s;

但是使用 thunk ,它似乎不起作用。

var s = stream(); 
yield thunk(url, s);
this.body = s;

这是thunk

var thunk = function (url, s) {
  return function(callback) {
    var req = http.request(url, function(res) {
      res.pipe(s);
    });
    s.on('close', function() {
      callback(null, null);
      console.log('req inner close');
    });
    req.end(null);
  }
}
4

1 回答 1

2

为此使用承诺(返回承诺,而不是重击)。离开我的头顶,所以你可能需要玩弄它:

function run(url, s) {
  return new Promise(function(resolve, reject) {
    var req = http.request(url, function(res) {
      res.pipe(s);
      res.on('end', function() {
        req.end();
      });
    });

    req.on('error', function(err) {
      return reject(err);
    });

    s.on('close', function() {
      console.log('req inner close');
      return resolve();
    });
  });
}

然后:

yield run(url, s);
于 2015-02-18T23:58:30.667 回答