マングースはすでに約束されているので、これでうまくいきます:
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);
});
Promiseは非同期であるため、Promiseを返すだけで、呼び出し元はPromiseが解決されるのを「待機」し、エラーを処理します。