search

Home  >  Q&A  >  body text

mongodb - Problem using then after mongoose save operation

This is my save operation, but the output order of the print statements is
B: undefined A: 正确内容

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

<code>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

    })

  })

})</code>

Why is the then operation executed first? Shouldn’t it be executed after my save promise returns?
I have specified mongoose.Promise = Promise;
I hope someone can help me solve it = =

阿神阿神2865 days ago641

reply all(2)I'll reply

  • 伊谢尔伦

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

    You got it mixed up,

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    <code class="js"> 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

        })

      })

    })</code>

    You put callback and promise together

    Link description

    reply
    0
  • 阿神

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

    Use return Promise.resolve(_new_replay) after successful save, do not return directly

    reply
    0
  • Cancelreply