如何在 koa 中使用 thunk 获取 readStream?

how to get readStream with thunk in koa ?

我想在 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);
  }
}

为此使用承诺(return 承诺,而不是 thunk)。不在我的脑海中,所以你可能需要尝试一下:

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);