The two pieces of code below throw a type error:
TypeError: Cannot read property 'then' of undefined.
I feel like I'm missing something fundamental. Remarkable is that the log of 'result' in the second piece of code is done after the error is thrown. Which leads me to believe I might be doing something wrong involving asynch. However I cannot get my head around it, even after reading the suggested questions.
Any help would be greatly appreciated!
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});
});
});
and from 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
fromthis.updateUser
. Doesexec
return a Promise?return result;
belongs to the callback you pass toexec
and not to the the function you assign tothis.updateUser
.