Correct request with async / wait in Node.JS

In my program, I call async call my function from another 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 like ?key=value&... key : value }, json: true } try { var result = await request(options); return result; } catch (err) { console.error(err); } } 

Execution is returned immediately, however result and, therefore, info contains the request object and the request body - info.body , like key=value&... , the response body is not required.

What am I doing wrong? How to fix? What is the correct use of request with async , or does it only work with promises, as indicated here: Why doesn't wait work for the node request module ? The following article mentioned is possible: Mastering Async Waiting in Node.js.

+5
source share
2 answers

You need to use the request-promise module, not the request module.

await working on functions that return a promise, not functions that return a request object, and expect you to use callbacks or event listeners to know when everything will be done.

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

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

 var request = require("request"); 

:

 var request = require("request-promise"); 
+12
source

I am sure you can also do the following. If what you need does not return Promise by default, you can provide it using the new Promise method. However, the answer above is less detailed.

 async function getBody(url) { const options = { url: url, method: 'GET', }; // Return new promise return new Promise(function(resolve, reject) { // Do async job request.get(options, function(err, resp, body) { if (err) { reject(err); } else { resolve(body); } }) }) } 
+1
source

Source: https://habr.com/ru/post/1271023/


All Articles