Javascript - 未更新的全局变量

时间:2014-06-02 13:08:45

标签: javascript jquery

我正在尝试更新回调函数中的全局变量(请参阅下面的代码)

function FunctionOne() {
    var result = "";

    for (var i = 0; i < 10; i++) {
         AjaxFunction(function (data) {
            result += data;
         });
    }

    alert(result);
}

function AjaxFunction(callback) {
    $.ajax({
        url: '/test',
        type: 'GET',
        success: function(data) {
            callback(data);
        }
    });
}

当我提醒result时,它似乎总是空白。你能告诉我什么错了吗?

2 个答案:

答案 0 :(得分:3)

结果不是全局的,它仅在FunctionOne()的范围内定义。但是在您的示例中,您在分配值之前警告该值,因为Ajax调用似乎异步运行。而是在更新您的价值后尝试提醒。

function FunctionOne() {
var result = "";

for (var i = 0; i < 10; i++) {
     AjaxFunction(function (data) {
        result += data;
        alert(result); // this should have the value
     }
}

alert(result); // this should be empty
}

答案 1 :(得分:1)

您的问题有两个部分需要解决 - 第一部分涉及AJAX的异步性质以及如何返回结果 - 请参阅the canonical answer to the question这最初标记为重复。< / p>

第二部分是如何根据所有十个 AJAX请求的异步完成来做出最终答案:

function functionOne() {
    // initiate ten requests, storing the promises in an array
    var def = [];
    for (var i = 0; i < 10; ++i) {
        def[i] = AjaxFunction();
    }

    // wait for all the promises to complete, with the
    // eventual result also being returned as a promise
    return $.when.apply($, def).then(function() {
        // take a copy of the arguments
        var args = [].slice.call(arguments, 0);   

        // concatenate them all together
        return args.reduce(function(prev, current) {
            return prev + current[0];   // each arg is actually a 3-element array
        }, "");
    });
}

function AjaxFunction() {
    return $.get('/test');  // NB: using promises - no callback required
};

// NB: functionOne() is now also async - you have to wait
//     for the promise to be resolved before using the result

functionOne().then(function(result) {
    alert(result);
)};

有关正常工作的演示,请参阅http://jsfiddle.net/alnitak/5s28G/