使用promise时出现重复的猫鼬日志条目
我已将承诺实现到猫鼬中,但是我收到重复的日志条目,并且不确定是否是预期的输出,如果是,为什么?
我运行以下函数,在if语句中仅运行一次。
const isUsernameTaken = (username) => {
let isTaken;
const promise = User.find({username: username}, (err, doc) => {
if(doc.length) {
isTaken = true;
} else {
isTaken = false;
}
}).exec();
promise.then(() => {
return isTaken;
});
}
猫鼬调试输出
Mongoose: users.find({username: 'test'}, {projection: {}})
Mongoose: users.find({username: 'test'}, {projection: {}})
true
vs我所期望的
Mongoose: users.find({username: 'test'}, {projection: {}})
true
回答如下:[似乎使用find
的回调,以及调用exec()
两次发送请求...将回调放入promise.then(...)
内可以解决此问题:
const isUsernameTaken = (username) => {
User.find({username: username})
.exec()
.then(doc => doc ? true : false)
.catch(err => console.log(err));
}