AJAX requests are asynchronous - this is what the first A means. If you have logic that depends on the data returned by the request, it should be placed in a callback function. Try the following:
var country, city = ''; function geoData() { $.getJSON('http://ipinfo.io/json?callback=?', function (data) { console.log('step 1'); country = data.country; city = data.city; console.log('step 2'); step3(); }); }; function step3() { console.log('step 3'); } geoData();
An alternative is to use a promise, although the logical flow is roughly equivalent:
var country, city = ''; function geoData() { return $.getJSON('http://ipinfo.io/json?callback=?', function (data) { console.log('step 1'); country = data.country; city = data.city; console.log('step 2'); }); }; var deferred = geoData(); $.when(deferred).done(function() { console.log('step 3'); });
source share