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

173
Visualizações
then() callback firing before promise is resolved in node.js

Using node.js version 7.7.2, I'd like to execute an asynchronous function and then a different function once the first function has completed like this:

function foo() {
  return new Promise(function(resolve, reject) {
    // Do some async stuff
    console.log('foo is about to resolve');
    resolve();
  });
}
    
function bar(arg) {
  console.log(arg);
}

foo().then(bar('bar has fired'));

The issue is that this setup prints 'bar has fired' followed by 'foo is about to resolve'. What I expect is that bar will wait to fire until the promise returned by foo has resolved. Am I misunderstanding how then() queues callbacks in the node.js event loop?

Thanks

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

As stated in a comment, pass a function to then that, when called, will call bar with your params.

function foo() {
  return new Promise(function(resolve, reject) {
    // Do some async stuff
    console.log('foo is about to resolve');
    resolve();
  });
}
    
function bar(arg) {
  console.log(arg);
}

foo().then(function(){bar('bar has fired')});

over 4 years ago · Santiago Trujillo 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