When dealing with promises in JavaScript, the then() method returns a promise that can be in one of three states: pending, fulfilled, or rejected. You can create a promise using the resolved and rejected methods to indicate when it should be fulfilled or rejected. However, sometimes using these methods within functions in the then() chain can be tricky, especially when working with normal asynchronous functions that have callbacks. Take the following example:
User.findOne({
where: {
email: email
}
}).then(function(user){
if(user){
return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
}else{
var user = User.build({ email: email });
console.log("ONE");
User.generateHash(password, function(err, hash){
console.log("TWO");
if(err){
return done(err);
}else{
user.password = hash;
var newUser = user.save();
return newUser;
}
})
}
}, function(err){
console.log("ERROR: ", err);
}).then(function(newUser){
console.log("THREE");
return done(null, newUser);
}, function(err){
console.log("USER NOT CREATED: ", err);
});
In this scenario, User.findOne() returns a promise that causes the console output to be ONE THREE TWO due to the asynchronous nature of the code execution. If you want to control when the second then statement gets executed, you may need to adjust your approach by properly handling the flow of promises in your code.
Although there are multiple ways to resolve this issue, understanding why and when the promise returned by the first statement becomes fulfilled is crucial for improving the overall performance and reliability of your code.