The then() method on promises returns a promise. A promise can be in one of three states, pending, fulfilled, or rejected. However when creating a promise you have a resolved and rejected method to call when you want your promise to be fulfilled or rejected. I can not find out how to use these methods on functions in the then() method. This has caused me problems when I am trying to use normal asynchronous functions with a callback in the middle of a then() chain. Take this code for 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 case User.findOne() returns a promise. Now the console for this would print ONE THREE TWO. The second then statement is called as soon as the asynchronous is called. Is there a way to not have the second then statement called until I notify it as resolved.
(I am aware this would be easy code to fix several different ways, I am more curious about why and when the then promise returned by the first statement becomes fulfilled.)