[英]Trying to unnest promises with mongoose queries
I currently have a create method that creates a new adventure, saves it, then adds the resulting adventure's ID to a user. 我目前有一个create方法,该方法可以创建一个新的冒险,将其保存,然后将生成的冒险的ID添加到用户。 The only problem is, it has nested promises and I'm wondering if there's a way to prevent that. 唯一的问题是,它嵌套了诺言,我想知道是否有防止这种诺言的方法。 The code: 编码:
function create(req, res) {
new Adventure(req.body)
.save()
.then(function (result) {
User.findByIdAndUpdate(
result.dm_id,
{ $push: { adventures: result._id }}
)
.exec()
.catch(fail); // FIXME: nested promises :(
res.status(200).send(result);
})
.catch(fail);
}
I think the catch here is that I need to send the response back with the adventure I created, rather than the user I add the adventure to. 我认为这里的收获是,我需要将响应与我创建的冒险一起发回,而不是将冒险添加到的用户。
Thanks! 谢谢!
If you return the promise that (your code implies) is returned by .exec - then you should be able to do something like this 如果您返回的承诺(您的代码所隐含的)由.exec返回-那么您应该能够执行以下操作
function create(req, res) {
new Adventure(req.body)
.save()
.then(function (result) {
var ret = User.findByIdAndUpdate(result.dm_id, { $push: { adventures: result._id }}).exec();
res.status(200).send(result);
return ret;
})
.catch(fail);
}
or 要么
function create(req, res) {
new Adventure(req.body)
.save()
.then(function (result) {
res.status(200).send(result);
return User.findByIdAndUpdate(result.dm_id, { $push: { adventures: result._id }}).exec();
})
.catch(fail);
}
not sure if it's "valid" to use res.status
line before the findByIdAndUpdate
line, so this second code block may be wrong 不知道是否是“有效”使用res.status
的前行findByIdAndUpdate
线,所以这第二个代码块可能是错误的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.