I'm trying to get user's city and country before moving on with my code. It seems as if javascript is not executed in the order I need.
$(document).ready(function() {
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');
});
};
geoData();
console.log('step 3');
/* rest of the code */
});
I want the code to be executed as:
step 1
step 2
step 3
However when I run the script I get:
step 3
step 1
step 2
Why is the code running in an asynchronous way? Any suggestions how I can fix it?
Thanks.
AJAX requests are asynchronous - it's what the first A stands for. If you have logic that depends on the data returned by the request, it needs to be placed within the callback function. Try this:
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 logic 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');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With