我想使用发布者功能将数据发送到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"
})
})
如何解决这个问题?也许我的结构很糟糕。如果情况非常糟糕,请对我说。
您需要从第一个then()
方法的回调函数返回result
。
todo.save()
.then(result => {
...
return result;
})
.then(result =>{
// access result
})
每个then()
方法调用都会返回一个Promise
,并且该Promise
是满足还是被拒绝,具体取决于您从该特定then()
方法的回调函数返回的内容。
如果从回调函数返回非 promise 值,则包装器then()
方法返回的Promise
将使用该值实现,并且该已实现的值将作为参数传递给下一个then()
方法的回调函数(如果存在)。
如果从then()
方法的回调函数返回Promise
,则该then()
方法返回的Promise
将解析为其回调函数返回的Promise
。这意味着then()
方法返回的Promise
将得到满足或拒绝,具体取决于其回调函数返回的Promise
会发生什么情况。
如果回调函数返回的Promise
是用非 promise 值实现的,则then()
方法返回的Promise
将使用相同的值实现,并且此值将作为参数传递给下一个then()
方法的回调函数(如果存在)。
也许我的结构很糟糕。如果情况非常糟糕,请对我说。
我不明白为什么你需要第二种then()
方法。您只需将数据传递给第一个then()
方法的回调函数中的natsPublisher()
函数。