最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

使用promise时出现重复的猫鼬日志条目

运维笔记admin11浏览0评论

使用promise时出现重复的猫鼬日志条目

使用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));
}
发布评论

评论列表(0)

  1. 暂无评论