Proper request with async/await in Node.JS

You need to use the request-promise module, not the request module or http.request().

await works on functions that return a promise, not on functions that return the request object and expect you to use callbacks or event listeners to know when things are done.

The request-promise module supports the same features as the request module, but asynchronous functions in it return promises so you can use either .then() or await with them rather than the callbacks that the request module expects.

So, install the request-promise module and then change this:

var request = require("request");

to this:

const request = require("request-promise");

Then, you can do:

var result = await request(options);

EDIT Jan, 2020 – request() module in maintenance mode

FYI, the request module and its derivatives like request-promise are now in maintenance mode and will not be actively developed to add new features. You can read more about the reasoning here. There is a list of alternatives in this table with some discussion of each one.

I have been using got() myself and it’s built from the beginning to use promises, supports many of the same options as the request() module and is simple to program.

Leave a Comment