Weather Project - Variable being returned before defined

Weather Project - Variable being returned before defined
0

#1

Hi there,
I’m currently completing my FreeCodeCamp Local Weather project, however I have run into a problem.

In the function below, a variable is being returned in it’s undefined state, before the getJSON() function can alter it. I can’t figure out how to make it return the correct value;

function getWoeid(lat, long) {
  var woeid;
  var url = 'https://www.metaweather.com/api/location/search/?lattlong='+lat+','+long;
  console.log(url);
  
  $.getJSON( "https://cors.io/?https://www.metaweather.com/api/location/search/?lattlong="+lat+","+long, function( data ) {
  console.log(JSON.stringify(data));
  woeid=data[0].woeid;
  console.log(woeid);
 
  });
return woeid;  
}

#2

You can’t (as far as I know). What you want to do with woeid must be done in the getJSON's callback function.

Actually, you sort of can return that value, but that involves using Promises.


#3

@kevcomedia Thanks, solved it using an async callback.

    getWoeid(position.coords.latitude,position.coords.longitude, function(data){
      globalWoeID = data[0].woeid;
     // x.innerHTML = globalWoeID;
    })

function getWoeid(lat, long, callback) {
  var woeid;
  var url = 'https://cors.io/?https://www.metaweather.com/api/location/search/?lattlong='+lat+','+long;
  console.log(url);
  
 $.getJSON(url, function( data ) {
  callback(data);
  console.log(JSON.stringify(data));
  this.woeid=data[0].woeid;
  console.log("get Json func" + this.woeid);
  
  });
  
}