Is $.when() or $.when.apply() the correct call for getting a promise out of a forEach?

24 Views Asked by At

I have a function processing an array, calling a function for each entry within the array with a Promise returned, and then finally returning that it's done.

var dealCardSelectableAI = function () {
  var deferred = $.Deferred();
  var deferredQueue = [];

  _.forEach(model.galaxy.systems(), function (system, starIndex) {
    if (model.canSelect(starIndex) && system.star.ai()) {
      deferredQueue.push(
        chooseCards({
          inventory: inventory,
          count: 1,
          star: system.star,
          galaxy: game.galaxy(),
          addSlot: false,
        }).then(function (result) {
          system.star.cardList(result);
        })
      );
    }
  });

  $.when.apply($, deferredQueue).then(function () {
    deferred.resolve();
  });

  return deferred.promise();
};

dealCardSelectableAI().then( /* other stuff */ )

Most stuff I find on promises is to do with ES6 and Promises.all(), but I'm working in ES5 so am using jQuery.

My understanding is that due to deferredQueue being of unknown length $.when.apply() is the correct call here rather than $.when(), but regardless of which I use everything seems to operate as expected.

Have I set this up correctly? Is $.when.apply() the correct call and am I using it right?

0

There are 0 best solutions below