Reputation: 208
I am trying to use http.request on node using the koajs framework. Is there a way I can utilize it as show below?
var http = require('http');
var result = yield http.request(options);
Upvotes: 2
Views: 767
Reputation: 9437
Presumably the problem you're facing is that http.request
takes a callback rather than returning a promise, so you can't yield
it from koa. You need to wrap http.request
in a function that returns a promise and hook the promise resolve into the callback, while also hooking the promise reject into the error handler.
function request(opts, body) {
return new Promise((resolve, reject) => {
body.pipe(http.request(opts, resolve))
.on('error', reject);
});
}
...later in your koa function...
var response = yield request(opts, body);
There are so many possible variations on this that I couldn't come close to listing them all, but that's the basic idea :)
Upvotes: 1