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

144
Vistas
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 Respuestas
Responde la pregunta

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