简体   繁体   English

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

[英]how to get readStream with thunk in koa ?

I want to pipe a request in a koa controller, It's work: 我想在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;

But with thunk , it seems to be not work. 但是随着重击,似乎是行不通的。

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

Here is the thunk : 这是重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);
  }
}

Use a promise for this (return a promise, not a thunk). 为此使用承诺(返回承诺,而不是笨拙)。 Off the top of my head, so you may need to play around with it: 离开我的头顶,所以您可能需要尝试一下:

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

Then: 然后:

yield run(url, s);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM