Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

96
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda