Waiting for function to complete - execution is asynchronous (not OK)

I am trying to get a custom city and country before moving on to my code. It seems that javascript is not executing 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 run as:

 step 1 step 2 step 3 

However, when I run the script, I get:

 step 3 step 1 step 2 

Why does the code work asynchronously? Any suggestions how can I fix this?

Thanks.

+6
source share
2 answers

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'); }); 
+8
source

Use jQuery promises to get the desired result, for example:

 var geoDataRequest = function () { var deferred = $.Deferred(); $.getJSON('http://ipinfo.io/json?callback=?', function (data) { deferred.resolve(data); }); return deferred.promise(); }; var somefunction = function () { // This will return a promise var getGeoData = geoDataRequest (); // The appropriate function will be called based on if the promise is resolved or rejected through the success and error functions in the AJAX request getGeoData.then( // Done response function (result) { alert("Success! "); // Enter logic here for step 2 and 3 }, // Fail response function (xhr, status, errorThrown) { // Handle errors here... } ); }; somefunction(); 

In addition, now you can use your geoDataRequest whenever you want, and process the results differently if you want!

+3
source

Source: https://habr.com/ru/post/990022/


All Articles