Are nested catches required within promises?

We would like to reduce the number of catch blocks inside our promises. If we remove nested catches, will exceptions be thrown before the parent catch?

temporaryUserModel.findOne({email: req.body.email}) .then(tempUser => { if (tempUser) { temporaryUserModel.findOneAndUpdate({_id: tempUser.toJSON()._id}, user) .then((doc) => { return res.status(200).json({ status: 'Success', data: {url: planOpted.chargifySignupUrl} }); }) .catch(err => error(err, res)); } else { temporaryUserModel(user).save() .then((doc) => { return res.status(200).json({ status: 'Success', data: {url: planOpted.chargifySignupUrl} }); }) .catch(err => error(err, res)); } }) .catch(err => error(err, res)); 

We would like to remove two nested catches and keep only the catch below. This is normal?

+6
source share
2 answers

No, they will not. They only bounce to the result if you bind your promises, for which you need to return internal promises created by the callbacks. Otherwise, the external promise cannot wait for them and will not know when / how they are decided (whether they fulfill or reject).

 temporaryUserModel.findOne({email: req.body.email}).then(tempUser => { if (tempUser) { return temporaryUserModel.findOneAndUpdate({_id: tempUser.toJSON()._id}, user); // ^^^^^^ } else { return temporaryUserModel(user).save(); // ^^^^^^ } }).then((doc) => { // no need to duplicate this code when you chain anyway return res.status(200).json({ status: 'Success', data: {url: planOpted.chargifySignupUrl} }); }).catch(err => error(err, res)); 
+5
source

You can extract part of the logic into separate functions and return internal promises to create all exceptions in the promise chain:

 temporaryUserModel.findOne({email: req.body.email}) .then(updateTempUser) .then(formatResponse) .catch(err => error(err, res)); function updateTempUser(tempUser) { if (tempUser) { return temporaryUserModel.findOneAndUpdate({ _id: tempUser.toJSON()._id }, user); } else { return temporaryUserModel(user).save() } } function formatResponse(doc) { return res.status(200).json({ status: 'Success', data: {url: planOpted.chargifySignupUrl} }); } 
+2
source

Source: https://habr.com/ru/post/1013532/


All Articles