Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!