I am looking for a way to return a promise only if another promise fails .
How can i do this?
promises that I look like this (of course, I delete the unrelated code):
getUserByUsername = function(username) {
return promise(function(resolve, reject) {
user = userModel.getByUsername(username);
if ( user ) { resolve(user); } else { reject("user not found"); }
});
};
getUserByEmail = function(email) {
return promise(function(resolve, reject) {
user = userModel.getByEmail(email);
if ( user ) { resolve(user); } else { reject("user not found"); }
});
};
checkPassword = function(user, password) {
return promise(function(resolve, reject) {
if ( user.isValidPassword(password) ) { resolve() } else { reject("password mismatch"); }
});
};
And I want to combine them in the following sequence
- Call
getUserByUsername, then reject, then callgetUserByEmail - Returns a whoever value that resolves from the two promises above OR, if both promises reject the entire chain.
- Call
checkPasswordwith value and, if he rejects, reject the whole chain
So far I have done this and it seems to work. (I use when.js btw)
getUserByUsername(usernameOrEmail)
.then(
function(user) { return user; },
function() { return getUserByEmail(usernameOrEmail) }
)
.then( function(user) { return checkPassword(user, password) } )
.done(
function() { console.log('success'); },
function(err) { console.log('failure', err) }
);
, , , ( , ).