简体   繁体   English

我可以声明一个非全局变量来存储异步值吗?

[英]Can I declare a non-global variable to store asynchronous values?

I have multiple JavaScript files. 我有多个JavaScript文件。 I have a JS function that runs upon load that contains multiple AJAX calls. 我有一个JS函数,在包含多个AJAX调用的负载下运行。 Each AJAX call performs a callback (as well as increments a synchronous counter):: myArray.push('somevalue'); 每个AJAX调用都会执行一个回调(并增加一个同步计数器):: myArray.push('somevalue');

so that I can verify when all AJAX calls (for this JS file) have finished. 这样我就可以验证所有(针对此JS文件的)AJAX调用何时完成。

Is there a way that I can get away with not declaring myArray as a global variable, while allowing asynchronous callbacks to push into this array? 有没有一种方法可以避免将myArray声明为全局变量,而又允许异步回调推入此数组呢?

If you want to execute some code after a set number of AJAX requests have completed, use $.when . 如果要在一定数量的AJAX请求完成后执行一些代码,请使用$.when

If you are using myArray solely to know when the requests are finished, you can remove it. 如果仅使用myArray来知道请求何时完成,则可以将其删除。 If you are using it to store the result of each request, you can keep it in the same scope as the requests and then access it in the done handler. 如果使用它来存储每个请求的结果,则可以将其保留在与请求相同的范围内,然后在done处理程序中对其done访问。 Try this: 尝试这个:

var myArray = [];

var ajax1 = $.ajax({
    url: '/foo/',
    success: function(data) {
        myArray.push(data);
    });
});

var ajax2 = $.ajax({
    url: '/bar/',
    success: function(data) {
        myArray.push(data);
    });
});

$.when(ajax1, ajax2).done(function() {
    // both requests complete
    // myArray will contain the data of both requests at this point...
    for (var i = 0; i < myArray.length; i++) {
        console.log(myArray[i]);
    }
});

Declare a variable that is only accessible within the scope you want it (eg, inside the function). 声明一个只能在所需范围内访问的变量(例如,在函数内部)。

Something like: 就像是:

var ajaxCalls = function() {
    var myArray = [];

    var ajax1 = $.ajax({
        url: 'foo.com',
        success: function(data) {
            myArray.push(data);
        });
    });

    // do more AJAX stuff

    $.when(ajax1, ..., ).done(function() {
        // make sure all requests are complete
        // do stuff with the completed array
    });
};

Since JavaScript has functional scoping, your myArray variable won't be global, but it will be accessible within the ajax callbacks. 由于JavaScript具有功能范围,因此myArray变量将不是全局变量,但可以在ajax回调中访问。 Hope that helps! 希望有帮助!

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

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