TypeError: promise.then(…).then(…).then(…).then(…)

2020-08-21 11:50发布

问题:

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.

回答1:

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/