Reputation: 5449
I have converted a lot of request.get to follow this new async/await pattern. Is there a way to do the same for request.post. Here's a sample code I have and would appreciate any input
try {
request({ url: url, method: 'POST', body: parameters, json: true}, function (error, response, body) {
if (!error) {
return res.status(200).send(response.body);
} else {
return res.status(500).send(response.body);
}
});
} catch(err) {
return res.status(500).send(err);
}
Upvotes: 0
Views: 2684
Reputation: 2974
You could wrap the request method in a Promise and then in an async function like so:
let request = require('request');
async function asyncRequest(options) {
return new Promise((resolve, reject) => {
request(options, (error, response, body) => resolve({ error, response, body }));
});
}
async function google() {
let response = await asyncRequest('http://www.google.com');
console.log(response.response.statusCode);
}
google();
According to the documentation for request
, you could use the request-promise
module to avoid doing the Promise wrapping yourself
Upvotes: 2