.When() and .done() using an array with .done

前端 未结 3 466
一整个雨季
一整个雨季 2020-12-07 05:08

I am writing a google content script and my program needs to make roughly 30 AJAX calls to the server. I am using JQuery\'s .when function in conjunction with .apply to pas

3条回答
  •  眼角桃花
    2020-12-07 06:01

    Are you looking to put the ajax responses in an array and have a callback execute when all the ajax calls have returned? You can actually get such an array from the arguments passed to .done().

    According to the documentation for $.when:

    1. If you call .done() on the Promise returned by $.when when it is passed a single ajax request Deferred, the first argument to the callback function will be the response data.
    2. If you call .done() on the Promise returned by $.when when it is passed multiple ajax request Deferreds, "the arguments will be the jqXHR objects for the requests, in the order they were given in the argument list." That statement appears to be a bit inaccurate, however, because a comment in the example states: "Each argument is an array with the following structure: [ data, statusText, jqXHR ]."

    Therefore you could try:

    var requests = $.map(liclass, function(url) {
        return $.ajax(url);
    });
    
    $.when.apply($, requests).done(function() {
        var results = (requests.length > 1)
            ? $.map(arguments, function(a) { return a[0]; })
            : [arguments[0]];
        console.log(results);
    });
    

    Demo on JSFiddle

提交回复
热议问题