等待函数完成 - 执行是异步的(不按顺序)

时间:2015-06-30 15:03:15

标签: javascript jquery

在继续使用我的代码之前,我正在努力获取用户的城市和国家/地区。似乎javascript没有按照我需要的顺序执行。

$(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 */
});

我希望代码执行为:

step 1
step 2
step 3

然而,当我运行脚本时,我得到了:

step 3
step 1
step 2

为什么代码以异步方式运行?有什么建议我可以解决它吗?

感谢。

2 个答案:

答案 0 :(得分:9)

AJAX请求是异步的 - 它是第一个A代表的东西。如果您的逻辑依赖于请求返回的数据,则需要将其置于回调函数中。试试这个:

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();

另一种方法是使用promise,尽管逻辑流程大致相同:

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

答案 1 :(得分:4)

使用jQuery promises获得所需的结果,如下所示:

myCursor = db.rawQuery("SELECT * FROM (SELECT * FROM (SELECT * FROM Answers
    WHERE QuestionID = 3 AND RightWrong = 0 ORDER BY RANDOM() LIMIT 3)
    UNION SELECT * FROM (SELECT * FROM Answers WHERE QuestionID = 3 AND
    RightWrong = 1 LIMIT 1)) ORDER BY RANDOM() LIMIT 4", null)

此外,您现在可以随时使用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(); ,并根据需要以不同方式处理结果!