搜尋

首頁  >  問答  >  主體

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;
希望有人幫我解下來= =

阿神阿神2832 天前628

全部回覆(2)我來回復

  • 伊谢尔伦

    伊谢尔伦2017-05-02 09:25:27

    你搞混了,

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

    連結描述

    回覆
    0
  • 阿神

    阿神2017-05-02 09:25:27

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

    回覆
    0
  • 取消回覆