2016-12-12 59 views
2

看看下面的例子:如何等待使用ajax調用完成的_.each循環?

_.each(arrayOfVals, function (val) { 
    $.when(getAjaxCall('foo',{val:val})) 
    .then(function (callResponse) { 
     _.each(callResponse, function (rep) { 
     console.log(rep); 
     }); 
}); 

然後我想打電話給一些代碼後,該代碼的全部完成。我怎樣才能做到這一點?

+1

使用Promise.all API – Bazinga

回答

0

我結束了使用$ .Deferred對象聽當一切都做,並呼籲決心,當我把整個名單了。

deferred = $.Deferred 
i = 0; 

_.each(arrayOfVals, function (val) { 
    $.when(getAjaxCall('foo',{val:val})) 
    .then(function (callResponse) { 
     _.each(callResponse, function (rep) { 
     i += 1; 
     console.log(rep); 
     if (i == callResponse.length) { 
      deferred.resolve(); 
     } 
     }); 
}); 

deferred.done(function() { 
    console.log('everything done!'); 
} 
1

您可以將多個參數傳遞給$.when,並且它的全部完成時它的延期將解決。如果您有陣列,請使用.apply

$.when.apply($, arrayOfVals.map(val => getAjaxCall('foo', {val})) 
    .then(responses => responses.map(resp => console.log(resp));