【发布时间】:2014-06-24 04:33:20
【问题描述】:
我正在尝试使用 Mongoose Promises 来获得更简洁的代码(请参阅嵌套函数)。 具体来说,我正在尝试构建这样的东西:
Model.findOne({_id: req.params.id, client: req.credentials.clientId}).exec()
.then(function(resource){
if (!resource) {
throw new restify.ResourceNotFoundError();
}
return resource;
})
.then(function(resource) {
resource.name = req.body.name;
return resource.save; <-- not correct!
})
.then(null, function(err) {
//handle errors here
});
因此,在其中一个承诺中,我需要保存我的模型。在最新的稳定版本中,Model.save() 不返回承诺(错误为 here)。
要使用经典的保存方法,我可以使用这个:
//..before as above
.then(function(resource) {
resource.name = req.body.name;
resource.save(function(err) {
if (err)
throw new Error();
//how do I return OK to the parent promise?
});
})
但正如代码中所注释的,我如何将保存回调(异步运行)的返回值返回到持有承诺?
有没有更好的办法?
(顺便说一句,findOneAndUpdate 对我来说是一个不可行的解决方案)
【问题讨论】: