user17422 user17422 - 5 months ago 7
Node.js Question

Obtaining a value from a request function and passing it into another request function

I have a request function to which I pass url1 and obtain a value called latitude and then use it to make a new url and pass it into another request function. So how do I use the value obtained in one request function outside of that request function

var url1= {some url}
var latitude;
request(url1, function (error1, response1, body1) {
if(error1){
return console.log('Error:', error1);
}
if(response1.statusCode !== 200){
return console.log('Invalid Status Code Returned:', response1.statusCode);
}
var obj1= JSON.parse(body1);
latitude = obj1.response.data[0].latitude;
});
//I want to use this latitude that to make a new url and use it another request function
var url 2 = {some url + latitiude}
request(url2, function (error2, response2, body2) {
if(error2){
return console.log('Error:', error2);
}
if(response2.statusCode !== 200){
return console.log('Invalid Status Code Returned:', response2.statusCode);
}
});
So how do I pass the latitude value from the first request function to the new url2? When I tried the latitude variable was not accesible outside the first request function.

Answer

You can use callbacks to pass the values obtained from first function to second function,

var url1= {some url}        
var latitude;   
request(url1, function (error1, response1, body1) {    
     //some code
     var obj1= JSON.parse(body1);    
     latitude = obj1.response.data[0].latitude;     

     var url2 = {some url + latitiude}    
     request(url2, function (error2, response2, body2) {    
        //some code          
     });  
});