[英]TypeError: Cannot read property 'then' of undefined (Promise) (node.js)
[英]Node Promise - TypeError cannot read property .then of undefined
下面的两段代码引发类型错误:
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});
});
});
并从userManager中:
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);
});
};
如果要使用Promises,则需要从this.updateUser
返回Promise, return result
属于您传递给exec
的回调,而不属于您分配给this.updateUser
的函数。
this.updateUser = function(id, data) {
return User.findOne({
_id: id
}).exec().then(function(user) {
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 = function(id, data) {
return User.findOne({
_id: id
}).exec().then(function(user) {
for (let prop in data) {
user[prop] = data[prop];
}
return user.save();
}).catch(function(err) {
console.log(err);
});
};
'updateUser'方法应返回一个Promise,以便第一个方法中的.then调用起作用。
尝试以下类似操作(使用的节点包“ q”)
this.updateUser = function(id, data) {
var deferred = Q.defer()
User.findOne({ _id: id }).exec(function(err, user){
if(err) {
console.log(err);
deferred.reject(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
deferred.resolve(resolve)
//return result;
}
}).catch(function(err){
deferred.reject(err)
console.log(err);
});
return deferred.promise
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.