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

前端 未结 3 456
一整个雨季
一整个雨季 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 05:57

    I'm fairly new to the deferred stuff (and jQuery in general), but my helper function below seems to work. None of the requests depend on each other for data. I'll probably write a similar helper function to handle chained requests, which will have to use .then().

    function sendRequests(requests, callbacks) {
        $.when(...requests).done(function(...results) {
                results.forEach(function(result, index) {
                        callbacks[index](JSON.parse(result[0]));
            });
        });
    }
    
    function req1Callback(data) {
        // do something with data object
    }
    
    var req1 = $.get(), // arguments omitted
        req2 = $.get(),
        req3 = $.get();
    
    sendRequests([ req1, req2, req3 ], [ req1Callback, req2Callback, req3Callback ]);
    

提交回复
热议问题