I'm new to NodeJS. I have an asynchronous function
request({url: 'url',json: true}, function (error, response, body) {});
I want to call a function only after this function is invoked. I can't call a .then() here. What are the other alternatives for this situation?
The await keyword is used to get a value from a function where you would normally use . then() . Instead of calling . then() after the asynchronous function, you would simply assign a variable to the result using await .
Async/await and then() are very similar. The difference is that in an async function, JavaScript will pause the function execution until the promise settles. With then() , the rest of the function will continue to execute but JavaScript won't execute the . then() callback until the promise settles.
The then() method returns a Promise . It takes up to two arguments: callback functions for the fulfilled and rejected cases of the Promise .
You could try something like this
return new Promise(resolve => {
request({
url: "",
method: "",
headers: {},
json: true
}, function (error, response, body) {
if(!error)
resolve(body);
})
}).then(value => {
// process value here
})
Just pass it as your callback function:
function callback (err, res, body) {
// Do what needs to be done here.
}
request({ url: 'url', json: true, someParam: true }, callback);
At the beginning of your callback function, check if err
exists and if so, handle the error.
This article might help you.
You can only call then
if your asynchronous function returns a Promise. But before you get into Promises, you should know the basics about Node.js.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With