Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
136
rated 0 times [  141] [ 5]  / answers: 1 / hits: 22362  / 9 Years ago, thu, november 12, 2015, 12:00:00

Im getting this error and i dont know how to solve it.
In a node js server, i'm using some .then() function on a promise and at the end i placed a .catch() function that for some reason is not recognized.
I have seen in many places in tutorials that this is how an error is handled.
I'm not using any external libraries.



The error :



 TypeError: promise.then(...).then(...).then(...).then(...).catch is not a function


This is my code:



exports.joinAlbum = function(req, res){


var promise = Album.findOne().where({'shortId': req.body.shortId}).exec(); // Returns a promise


promise.then(function(albumDoc){
console.log('Then #1');

.....

}
return albumDoc.save(); // Returns a promise
})



.then(function(albumDoc){
console.log('Then #2');

.....

return User.findById(req.body.userId).exec(); // Returns a promise
})


.then(function(userDoc){
console.log('Then #3');

........

return userDoc.save(); // Returns a promise
})

// Return a response
.then(function(savedUserDoc){
console.log('Then #4');
return res.status(200).json({success: true});
})

//Error handler
.catch(function(err){
console.log('Catch #1');
console.log(err);
res.status(200).json({success: false});
});
}


If .catch() is not the correct way to handle promise error, what do you suggest? Im trying to avoid using external libraries and prefer using native javascript



EDIT: solution



I added a npm module called blue-bird that helped me solve this.


More From » node.js

 Answers
15

It looks like you're using Mongoose, which returns its own Promise, not the ES6 promise which includes a catch function. A mongoose Promise has no catch function. You can overwrite the default Promise that Mongoose uses, fortunately:



http://eddywashere.com/blog/switching-out-callbacks-with-promises-in-mongoose/


[#64419] Tuesday, November 10, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kevenirvina

Total Points: 315
Total Questions: 112
Total Answers: 84

Location: Vanuatu
Member since Fri, May 13, 2022
2 Years ago
;