mongodb - mongoose save操作后使用then的问题

查看:413
本文介绍了mongodb - mongoose save操作后使用then的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

这是我的save操作,但是打印语句的输出顺序为
B: undefined A: 正确内容

router.post('/reply', (req, res, next) => {
  let topic_id = req.body.topic_id,
      content  = req.body.content

  let replyEntity = new replyModel({
    author: req._id,
    topic: topic_id,
    content
  })
  replyEntity.save((err, _new_reply) => {
    if (err) {
      return res.json({
        status: -1
      })
    }
    console.log('A: '+_new_reply)
    return _new_reply
  })
  .then((reply) => {
    console.log('B:  '+reply)
    return res.json({
      status: 0
    })
  })
})

为什么then操作内容会先执行呢,不应该等待我的save promise 返回回去才执行的吗?
我已经指定了mongoose.Promise = Promise;
希望有人帮我解决下啊= =

解决方案

你搞混了,

 replyEntity.save((err, _new_reply) => {
    if (err) {
      return res.json({
        status: -1
      })
    }
    console.log('A: '+_new_reply)
    return _new_reply
  })
  .then((reply) => {
    console.log('B:  '+reply)
    return res.json({
      status: 0
    })
  })
})

你把callback和promise弄到一起了

链接描述

这篇关于mongodb - mongoose save操作后使用then的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆