首页 > 解决方案 > Express,第二次调用then()函数,用猫鼬保存对象后返回未定义对象

问题描述

我想通过发布者功能将数据发送到 nats 流服务器。为此,我需要一秒钟然后在猫鼬模型保存上起作用。但是当我第二次调用 then() 函数时, 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"
   })
})

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

标签: javascriptnode.jsexpressmongoosepromise

解决方案


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

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

每个then()方法调用都会返回 a Promise,并且Promise根据您从该特定then()方法的回调函数返回的内容来完成或拒绝。

如果您从回调函数返回一个非承诺值,Promise则包装器then()方法返回的值将用该值实现,并且该实现的值将作为参数传递给下一个then()方法的回调函数(如果存在)。

如果Promise从方法的回调函数返回 a then(),则该方法Promise返回的值then()解析为其Promise回调函数返回的值。这意味着该方法Promise返回的then()内容将被执行或拒绝,具体取决于Promise其回调函数返回的内容。

如果Promise回调函数返回的值是非承诺值,则Promise该方法返回的值then()会满足相同的值,并且该值作为参数传递给下一个then()方法的回调函数(如果存在)。

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

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


推荐阅读