jQuery / deferreds:当多个.get完成时被通知

时间:2015-10-27 04:23:51

标签: jquery promise jquery-deferred

我已经编写了这段代码,以便从多个网址中获取内容。我想知道所有$.get调用何时满足:

foo : function(arrIds){
    var arrJqxhr = [];
    var arrReturnedData = []
    for ( var i = 0, l = arrIds.length; i < l; i++ ) {
        var url = '/thing/' + arrIds[i].toString()
        arrJqxhr[i] = $.get(url)
            .done(function(data, textStatus, jqXHR) {
                arrReturnedData.push(data);
            })
    }

除了保持被调用.done多少次之外还有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用$.when

 var arrReturnedData = [];
 var arrJqxhr = $.map(arrIds, function (id) {
     var url = '/thing/' + id.toString()
     return $.get(url)
         .done(function (data, textStatus, jqXHR) {
         arrReturnedData.push(data);
     })
 });

$.when.apply($, arrJqxhr).then(function(){
    //this will be called once all requests are successfully completed
    $.each(arguments, function(i, arr){
        arrReturnedData.push(arr[0])
    });
});