gpt4 book ai didi

javascript - Node promise - TypeError 无法读取未定义的属性 .then

转载 作者:行者123 更新时间:2023-12-03 04:54:10 25 4
gpt4 key购买 nike

下面的两段代码抛出类型错误:

类型错误:无法读取未定义的属性“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);
});

};

最佳答案

如果你想使用 Promise,你需要从 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);
});
};

关于javascript - Node promise - TypeError 无法读取未定义的属性 .then,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42505269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com