javascript - 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"
})
})
我怎么解决这个问题?也许我的结构很糟糕。如果非常糟糕,请告诉我。
解决方案
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()
推荐阅读
- angular - Angular:如何动态更改 scss 变量?
- ios - 我正在尝试从 Swift subreddit 解析 JSON。为什么我有问题?
- xamarin - 有没有办法使用 MvvmCross 在 Xamarin Forms 中使用嵌套的 CollectionViews?
- c++ - 基于范围的循环,自动引用指针
- redis - 如何使用生菜反应api处理get命令的空响应
- flowtype - 流返回错误的类型
- java - 如何将其转换为 Mockito 2.2?
- c# - 无法从 MVC 发送邮件
- python - 如何在定义函数时消除python中的索引错误
- node.js - 如何在 AppEngine 上使用 Angular 提供静态文件