rest - Proper request with async/await in Node.JS -


in program make async call function api module:

var info = await api.myrequest(value); 

module code:

var request = require("request")  module.exports.myrequest = async function myrequest(value) {     var options = {         uri: "http://some_url",         method: "get",         qs: {  // query string ?key=value&...             key : value         },         json: true     }      try {         var result = await request(options);         return result;     } catch (err) {         console.error(err);     } } 

execution returns immediately, result , therefore info contains request object , request body - info.body key=value&..., not required response body.

what i'm doing wrong? how fix? proper request usage async, or works correctly promises mentioned here: why await not working node request module? following article mentioned possible: mastering async await in node.js.

you need use request-promise module, not request module.

await works on functions return promise, not on functions return request object , expect use callbacks or event listeners know when things done.

the request-promise module supports same features request module, asynchronous functions in return promises can use either .then() or await them rather callbacks request module expects.

so, install request-promise module , change this:

var request = require("request"); 

to this:

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

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -