Mongoose est déjà promis, donc ceci fera l'affaire :
function findUser() {
return User.findOne({ "username": req.body.username })
.then(function(user) {
if (user) {
// user exists, you can throw an error if you want
throw new Error('User already exists!');
}
// user doesn't exist, all is good in your case
}, function(err) {
// handle mongoose errors here if needed
// rethrow an error so the caller knows about it
throw new Error('Some Mongoose error happened!');
// or throw err; if you want the caller to know exactly what happened
});
}
findUser().then(function() {
// user doesn't exist, do your stuff
}).catch(function(err) {
// here, you'll have Mongoose errors or 'User already exists!' error
console.log(err.message);
});
Une promesse est asynchrone, donc ne renvoyez que la promesse et l'appelant "attendra" qu'elle soit résolue et gérera les erreurs.