简体   繁体   中英

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

I have multiple JavaScript files. I have a JS function that runs upon load that contains multiple AJAX calls. Each AJAX call performs a callback (as well as increments a synchronous counter):: myArray.push('somevalue');

so that I can verify when all AJAX calls (for this JS file) have finished.

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?

If you want to execute some code after a set number of AJAX requests have completed, use $.when .

If you are using myArray solely to know when the requests are finished, you can remove it. 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. 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. Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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