Why await is not working for node request module?

user43286 picture user43286 · Jul 18, 2016 · Viewed 83.7k times · Source

I'm new to nodejs. I’m not seeing the response in ex 1, but i see in ex 2. Why? Await works for me in other places, using babel.

Ex 1

 let res = await request(url)
 console.log(res);
 console.log(res.body);

Ex 2

request(url, function (error, res, body) {
 if (!error && response.statusCode == 200) {
 console.log(body) 
 }
});

Await works in other places, I’m using babel and required modules for es6 and es7 features. For example, await works in squelize call, i validated. But it doesn’t work for request call. Why?

Answer

Saad picture Saad · Jul 18, 2016

You should only await on something that returns a Promise. I would definitely recommend reading up on Promises before you start working with async and await. You can probably get this example to work by creating your own wrapper function around request to make it return a promise, like so:

function doRequest(url) {
  return new Promise(function (resolve, reject) {
    request(url, function (error, res, body) {
      if (!error && res.statusCode == 200) {
        resolve(body);
      } else {
        reject(error);
      }
    });
  });
}

// Usage:

async function main() {
  let res = await doRequest(url);
  console.log(res);
}

main();

Edit: Alternatively, you can look into using a promise-based request library instead of the regular request module.