Luwak sudah dijanjikan, jadi ini akan dilakukan:
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);
});
Janji tidak sinkron sehingga hanya mengembalikan Janji dan penelepon akan "menunggu" untuk diselesaikan dan menangani kesalahan.