Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!