Return value of inner function from outer function?

Return value of inner function from outer function?
0

#1

Hi guys, this is the first time I’m REALLY stucked. Thing is I have this code:

function getLon(){ 
   var lon; 
   $.getJSON("http://ip-api.com/json", function(pos){
      lon = (pos.lon).toString(); 
   }); 
return lon; };

And (of course) lon isn’t in the scope of the outer function, so it doesn’t return anything. My question is, how could I return the lon value using the $.getJSON?

Thanks.


#2

The problem is that $.getJSON is asynchronous and you want to use it like it were synchronous. I’d suggest you to read up on the topic, it’s something you will definitely need later.

Anyway, you can work with the lon variable inside your callback or you can use promises. I hope it helps and can’t wait to see your weather app. :wink:


#3

Thanks zsoltime, I’ve read it but my code doesn’t work, I think I didn’t understand the way it works…:

var lon = {
  html: function() {
    return $.getJSON('http://ip-api.com/json').then(function(data) {
      return data.lat;
    });
  }
};

lon.html().done(function(html) {
  $("body").append(html);
});

This should do something, right? Even if I copy/paste de example code, it doesn’t work :confused:


#4

watch this it should help … https://channel9.msdn.com/Series/Javascript-Fundamentals-Development-for-Absolute-Beginners/Using-jQuery-to-Retrieve-JSON-via-AJAX-19


#5

It does actually, it appends the latitude of my location to the body. What error do you get, if any?


#6

No errors shown. It just doesn’t show anything.

Here’s my attempt. I just want two variables (lat & lon) to acquire the latitude and longitude given by this request and use these variables at the openweathermap request.

The only thing I could do from my point of view is to store the data in a hidden div and get it back in the request, but I know it must be a better way to do it. A correct way to do it. And I’m stucked already two whole days, it’s frustating.


#7

Ok, I managed to get some data. The answer was simplier than I could imagine… the problem now is that I’m doing a request by IP and the location isn’t exact.