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

125
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
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