【问题标题】:Express, calling then() function second times, return undefined object after saving an object with mongooseExpress,第二次调用then()函数,用猫鼬保存对象后返回未定义对象
【发布时间】:2021-05-23 20:06:45
【问题描述】:

我想通过发布者功能向 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"
   })
})

我该如何解决这个问题?也许我的结构很糟糕。如果很糟糕,请告诉我。

【问题讨论】:

    标签: javascript node.js express mongoose promise


    【解决方案1】:

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

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

    每个then() 方法调用都会返回一个Promise,并且Promise 是被满足还是被拒绝,具体取决于您从该特定then() 方法的回调函数返回的内容。

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

    如果您从then() 方法的回调函数返回Promise,则该then() 方法返回的Promise解析 为由返回的Promise它的回调函数。这意味着 then() 方法返回的 Promise 将被执行或拒绝,具体取决于其回调函数返回的 Promise 发生的情况。

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-01-30
      • 1970-01-01
      • 1970-01-01
      • 2018-07-12
      • 2018-07-08
      • 2017-04-04
      • 2015-05-31
      • 2021-09-03
      • 2020-08-08
      相关资源
      最近更新 更多