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

158
Vistas
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 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