繁体   English   中英

表达,第二次调用 then() function,在用 Z758D31F351CE11CBF20ZC52 保存 object 后返回未定义的 object

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

我想通过发布者 function 将数据发送到 nats 流服务器。 为此,我需要第二个然后 function 上 mongoose model 保存。 但是当我第二次调用 then() function 时, then(result => {})结果返回为未定义。

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"
   })
})

我怎么解决这个问题? 也许我的结构很糟糕。 如果非常糟糕,请告诉我。

您需要从第一个then()方法的回调 function 返回result

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

每个then()方法调用都会返回一个Promise ,并且Promise要么被满足,要么被拒绝,这取决于你从该特定then()方法的回调 function 返回的内容。

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 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. 这意味着then()方法返回的Promise将被执行或拒绝,具体取决于其回调Promise返回的 Promise 发生的情况。

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()方法,如果存在的话。

也许我的结构很糟糕。 如果非常糟糕,请告诉我。

我不明白你为什么需要第二个then()方法。 您可以在第一个then()方法的回调 function 中将数据传递给natsPublisher() function。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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