my node server needs to connect with other server in order to get some info and send it to the user. Since request is async in this situation I usually use addition libraries such as request-promise. But here I've got multiple calls from many points so I've created one function to handle them and this solution doesn't work.
apiCall1: function(req,res){
var info = fetchFromOtherServer();
console.log(info); // undefined
res.send(info)
}
apiCall2: function(req,res){
var info = fetchFromOtherServer();
console.log(info); // undefined
res.send(info)
}
function fetchFromOtherServer(){
var options = {"method":"POST", "headers":{...},"uri":"{...}"}
request(options, function(err,response,body){
if(!err && response.statusCode == 200){
console.log(body) // here is a body from other server
return body;
}
}
}
So first I get an api call to function apiCall() which calls fetchFromOtherServer function. But before request is done node marks info variable as undefined and send it to the user. How can I change my code to tell node to wait until I get a response from that other server?