如何避免同步XMLHttpRequest

时间:2015-04-26 22:46:13

标签: javascript ajax asynchronous synchronous

我正在为我们的QA团队构建Chrome扩展程序。在启动时,扩展会加载配置文件并使用它来设置全局对象的属性。这是代码:

var qaExt = (function() {

'use strict';

// Properties fetched from config file
var userHash, gitHash;

function getBuildInfo() {

    var xhr = new XMLHttpRequest();
    xhr.overrideMimeType("application/json");
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var buildInfo = JSON.parse(xhr.responseText);

            teamId  = buildInfo.teamId;
            gitHash = buildInfo.gitHash;
        }
    };

    var path = ((vAPI.firefox) ? '/content' : '') + '/js/build_info.json';

    xhr.open("GET", path, false);
    xhr.send();
}

return {

    isDev: true,
    userSettings: {
        collapseAllowed: true,
        menuEnabled: true,
        experimental: false
    },
    teamId: teamId,
    gitHash: gitHash,
};

})();

其他文件中的代码取决于属性' teamId'并且' gitHash'。这就是我在这里同步加载配置文件的原因。但是我在控制台中收到以下警告:

Synchronous XMLHttpRequest on the main thread is deprecated because of 
its detrimental effects to the end user's experience. For more help, 
check http://xhr.spec.whatwg.org/.

如果没有同步AJAX请求,我怎么能这样做?在设置这些值之前,我不希望其他代码执行。

1 个答案:

答案 0 :(得分:3)

只需使用回调函数。

function getBuildInfo(callback) {

    var xhr = new XMLHttpRequest();
    xhr.overrideMimeType("application/json");
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var buildInfo = JSON.parse(xhr.responseText);

            teamId  = buildInfo.teamId;
            gitHash = buildInfo.gitHash;
            callback();
        }
    };

    var path = ((vAPI.firefox) ? '/content' : '') + '/js/build_info.json';

    xhr.open("GET", path, true);
    xhr.send();
}

getBuildInfo(function(){
 //ajax request success and done.

});

以下是return语句的第二个选项:

function getBuildInfo(callback) {

    var xhr = new XMLHttpRequest();
    xhr.overrideMimeType("application/json");
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var buildInfo = JSON.parse(xhr.responseText);
            callback(buildInfo.teamId, buildInfo.gitHash);
        }
    };

    var path = ((vAPI.firefox) ? '/content' : '') + '/js/build_info.json';

    xhr.open("GET", path, true);
    xhr.send();
}

getBuildInfo(function(teamId, gitHash){
 //ajax request success and done.

});