【发布时间】:2017-07-19 05:14:40
【问题描述】:
下面两段代码抛出类型错误:
TypeError: 无法读取未定义的属性“then”。
我觉得我缺少一些基本的东西。值得注意的是,第二段代码中的“结果”日志是在抛出错误后完成的。这让我相信我可能做错了涉及异步的事情。但是,即使在阅读了建议的问题之后,我也无法理解它。
任何帮助将不胜感激!
router.route('/user/:id')
.put(auth.authRest, function(req, res) {
userManager.updateUser(req.params.id, req.body)
.then(function(response) { // line where error is thrown
res.send({data:response});
});
});
来自用户管理器:
this.updateUser = function(id, data) {
User.findOne({ _id: id }).exec(function(err, user){
if(err) {
console.log(err);
} else {
for(let prop in data) {
user[prop] = data[prop];
}
var result = user.save().catch(function(err){
console.log(err);
});
console.log(result); // this log is done below the error, it does contain a promise
return result;
}
}).catch(function(err){
console.log(err);
});
};
【问题讨论】:
-
您不会从
this.updateUser返回Promise。exec是否返回 Promise? -
嗯,当记录结果时它告诉我它包含一个承诺,怎么会?
-
return result;属于你传递给exec的回调,而不是你分配给this.updateUser的函数。
标签: javascript node.js mongoose promise