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;
希望有人帮我解决下啊= =

阅读 5k
2 个回答

你搞混了,

 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弄到一起了

链接描述

save 成功后使用return Promise.resolve(_new_replay),不要直接return

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进