Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

101
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda