Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative for .then() after request()

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?

like image 370
user231124ns11 Avatar asked Jun 01 '17 07:06

user231124ns11


People also ask

How do you use await instead of then?

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 .

Which is better async await or then?

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.

Is then () a promise?

The then() method returns a Promise . It takes up to two arguments: callback functions for the fulfilled and rejected cases of the Promise .


2 Answers

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
})
like image 163
iyerrama29 Avatar answered Nov 10 '22 11:11

iyerrama29


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.

like image 39
Josh Avatar answered Nov 10 '22 10:11

Josh