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

143
Visualizações
JavaScript promise is not frozen and next line is executed

I have a function that returns a promise:

const validateForm = () => {
    return new Promise((resolve, reject) => {
         // code here takes time
         return resolve('valid');
    });
}

And I use this promise this way:

validateForm()
.then(function(result) {
   console.log('form is valid');
})

console.log('line after promise');

I expect to see this output:

form is valid
line after promise

But I see this output:

line after promise
form is valid

How should I fix this code to get the first result? How freeze the code to not execute lines after promise until promise is either resolved or rejected?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

When using promises, all of the code at a given "level" is run first, then async / promises are run, which may then trigger thens.

1 validateForm()
2 .then(function(result) {
3    console.log('form is valid');
4 })
5 
6 console.log('line after promise');

In your code, it would essentially go line 1 and 6, then line 2, 3, 4 when the promise resolves.

You are trying to force async code to run synchronously, which just doesn't work. If you want your expected output, everything has to be in a then:

validateForm()
.then(function(result) {
   console.log('form is valid');
}).then(function () {
   console.log('line after promise');
});

Or it could be in the same then() just on the next line. But it can't just be out there.

Or you could be getting confused by seeing things that use async/await. If you're in an async function, you can do:

await validateForm()
.then(function(result) {
   console.log('form is valid');
})
   
console.log('line after promise');

Which is basically just syntaxical sugar for the above (though does tend to be people's preference, including mine).

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