Mongoose is al beloofd, dus dit is voldoende:
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);
});
Een Belofte is asynchroon, dus stuur alleen de Belofte terug en de beller zal "wachten" totdat deze is opgelost en de fouten afhandelen.