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?
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).