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

163
Visualizações
await for all promised to complete and then execute rest of the code

I have this code, I want the code to run for the first 3 push, on execution of the 4th push it should wait for all the promises to complete and then continue the execution. I am not sure if Promise.all is the right way or if there is something wrong with the logic.

var counter = 1;
function TaskRunner(concurrency) {
  this.concurrency = concurrency;
  this.waitList = [];
}

TaskRunner.prototype.push = async function (task) {
  let currentPromise = 'promise'+counter;
  if(counter <= this.concurrency) {
    this[currentPromise] = new Promise((resolve) => {
      resolve(task());
    });
    this[currentPromise].then(() => {
      console.log('completed: ', currentPromise);
    }).catch((e) => {
      console.log('failed: ', currentPromise);
    });
    this.waitList.push(this[currentPromise]);
    counter++;
    return;
  }
  if (counter === this.concurrency + 1) {
    return await Promise.all([this.waitList]).then((values) => {
      console.log('all resolved: ', values);
      task();
      counter++;
    }).catch(() => console.log('error'));
  }
  if (counter > this.concurrency) {
    counter++;
    task();
    return;
  }
  return;
};

function exampleTask() {
  setTimeout(() => console.log('done'), 5000);
}

var r = new TaskRunner(3);

r.push(exampleTask);
r.push(exampleTask);
r.push(exampleTask); 
r.push(exampleTask); // want to wait here for all promise to complete and then continue
r.push(exampleTask);
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