1

I am trying to use the data from one api in another so i need to use the variable in another function call but it is getting undefined even after i've initialized it globally.

  var latitude,longitude;
    var cityn=req.body.cityname;
    const appid="..."
    var unit="metric"
    
    const url1="https://api.openweathermap.org/geo/1.0/direct?q="+cityn+"&limit=5&appid="+appid
    
    https.get(url1,function(response){
       
        response.on("data",function(da){
            const CityDetails=JSON.parse(da);
            latitude=CityDetails[0].lat;
            longitude=CityDetails[0].lon;
            console.log(latitude) //--> defined
            console.log(longitude) //--> defined 
        })
    
    })
    console.log(latitude) //--> undefined
    console.log(longitude) //--> undefined 
    const url2="https://api.openweathermap.org/data/2.5/weather? lat="+latitude+"&lon="+longitude+"&appid="+appid+"&units="+unit;

I tried initializing it globally and also without using 'var' 'const' but both of the ways are not working.

inf3rno
  • 24,976
  • 11
  • 115
  • 197

1 Answers1

-1

This is because you want to log the lat-long data before it arrives from the server. You need to await the call before doing so or use synchronous HTTP request.

Better to use async-await for this kind of stuff. You can wrap the node.js HTTPS lib with this code:

function doRequest(options, data) {
  return new Promise((resolve, reject) => {
    const req = https.request(options, (res) => {
      res.setEncoding('utf8');
      let responseBody = '';

      res.on('data', (chunk) => {
        responseBody += chunk;
      });

      res.on('end', () => {
        resolve(JSON.parse(responseBody));
      });
    });

    req.on('error', (err) => {
      reject(err);
    });

    req.write(data)
    req.end();
  });
}

https://stackoverflow.com/a/56122489/607033

You can use it this way:

var latitude,longitude;
var cityn=req.body.cityname;
const appid="..."
var unit="metric"

(async function (){
    const options = {
        hostname: 'api.openweathermap.org',
        port: 443,
        path: "/geo/1.0/direct?q="+cityn+"&limit=5&appid="+appid,
        method: 'GET'
    };
    var CityDetails = await(doRequest(options));
    latitude=CityDetails[0].lat;
    longitude=CityDetails[0].lon;
    console.log(latitude);
    console.log(longitude);
    const options2 = {
        hostname: 'api.openweathermap.org',
        port: 443,
        path: "data/2.5/weather? lat="+latitude+"&lon="+longitude+"&appid="+appid+"&units="+unit,
        method: 'GET'
    };
    var data2 = await(doRequest(options2));
})();
inf3rno
  • 24,976
  • 11
  • 115
  • 197