我想在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);
}
}
答案 0 :(得分:2)
使用承诺(返回承诺,而不是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);