1

I want to pipe a request in a koa controller, It's work:

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:

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);
  }
}
elrrrrrrr
  • 894
  • 8
  • 15

1 Answers1

2

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);
danneu
  • 9,244
  • 3
  • 35
  • 63