Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS wait for HTTP request

I want to write an application that requests a token from an API. As long as this token isn't available I don't want to continue with the rest of the application. So it has to be like a synchronous HTTP request.

My goal is to create a function that does the request and then returns the token like:

var token=getToken();  //After this function has finished
makeRequest(token);   //I want this function to be executed

How can I do this?

like image 829
Apatus Avatar asked Mar 09 '17 17:03

Apatus


1 Answers

It doesn't want to be synchronous at all. Embrace the power of callbacks:

function getToken(callback) {
    //get the token here
    callback(token);
};

getToken(function(token){
    makeRequest(token);
});

That ensures makeRequest isn't executed until after getToken is completed.

like image 54
Taintedmedialtd Avatar answered Oct 02 '22 10:10

Taintedmedialtd