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

124
Vistas
JavaScript not waiting on promise to resolve

In the following code, what I'm after is to get the alert, after the counting is finished in the setInterval. The alert shows first though, and then the counting happens. What have I done wrong?

function function1() {
  return new Promise((resolve, reject) => {
    console.log('in function1 ')
    function2().then(resolve());
  });
}

function function2() {
  return new Promise((resolve, reject) => {
    var x = 0;
    I = setInterval(function() {
      console.log(x);
      if (x > 10) {
        clearInterval(I);
        resolve()
      };
      x++
    }, 100);
  });
}

function1().then(alert('finished'));

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Promise#then's first argument:

onFulfilled : A Function called if the Promise is fulfilled. This function has one argument, the fulfillment value. If it is not a function, it is internally replaced with an "Identity" function (it returns the received argument).

You can either pass a function name or a function as below:

function function1() {
  return new Promise((resolve, reject) => {
    console.log('in function1 ')
    function2().then(resolve); // onFulfilled
  });
}

function function2() {
  return new Promise((resolve, reject) => {
    var x = 0;
    I = setInterval(function() {
      console.log(x);
      if (x > 10) {
        clearInterval(I);
        resolve()
      };
      x++
    }, 100);
  });
}

function1().then(() => alert('finished')); // onFulfilled

about 4 years ago · Juan Pablo Isaza Denunciar
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