简体   繁体   中英

Express, calling then() function second times, return undefined object after saving an object with mongoose

I want to sending data to nats streaming server with publisher function. For that I need a second then then function on mongoose model save. But when I call second times then() function, then(result => {}) result is return as undefined.

todo.save().then(result =>{
   console.log(result)
   res.status(201).json({
       message : "done",
       todo : result
   });
}).then(result =>{
       console.log(result); // ===> this return undefined
       //natsPublisher(result.title, result.context); ===> I want to send this info to nats streaming
})
.catch(err=>{
   console.log(err);
   res.status(500).json({
       message : "There is an error"
   })
})

How can I solve this problem? Maybe my structure is very bad. If it is very bad please say to me.

You need to return result from the callback function of the first then() method.

todo.save()
 .then(result => {
    ...
    return result;      
 })
 .then(result =>{
    // access result
 })

Each then() method call returns a Promise and that Promise is either fulfilled or rejected depending on what you return from the callback function of that particular then() method.

If you return a non-promise value from the callback function, the Promise returned by the wrapper then() method will get fulfilled with that value and that fulfilled value will be passed as an argument to the callback function of the next then() method, if it exists.

If you return a Promise from the callback function of the then() method, then the Promise returned by that then() method will get resolved to the Promise returned by its callback function. This means that Promise returned by the then() method will either get fulfilled or rejected depending on what happens to the Promise returned by its callback function.

If the Promise returned by the callback function is fulfilled with a non-promise value, the Promise returned by the then() method gets fulfilled with that same value and this value is passed as an argument to the callback function of the next then() method, if it exists.

Maybe my structure is very bad. If it is very bad please say to me.

I don't see why you need the second then() method. You can just pass the data to the natsPublisher() function in the callback function of the first then() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM