Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for function to finish - execution is asynchronous (not in order)

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.

like image 705
tamiros Avatar asked Jun 30 '15 15:06

tamiros


1 Answers

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');
});
like image 101
Rory McCrossan Avatar answered Nov 15 '22 13:11

Rory McCrossan