How can I use the "http" module in koa?

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

Answers


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


Need Your Help

Running a WPF control in another thread

c# wpf multithreading task-parallel-library blocking

I am using a visual control in my project that is from a library that I do not have the source to.

Use buttons to post to a php script

javascript php button

Basically I am going to have a control panel for an application I'm working on that is just an array of buttons. I want to pass information about which button was pressed to the script that will ha...