繁体   English   中英

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

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

在继续使用我的代码之前,我正在尝试获取用户的城市和国家/地区。 似乎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

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

谢谢。

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

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

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

此外,您现在可以随时使用geoDataRequest ,并根据需要以不同方式处理结果!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM