如何等待 _.each 循环与 ajax 调用完成?

How to wait for _.each loop with ajax call to complete?

举个例子:

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

然后我想在整个代码完成后调用一些代码。我该怎么做?

您可以将多个参数传递给 $.when,它的延迟将在它们全部完成时解析。如果您有数组,请使用 .apply.

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

我最终使用 $.Deferred 对象来监听所有内容何时完成,并在遍历整个列表后调用 resolve。

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!');
}