Are nested catches within promises required?

前端 未结 2 2052
执笔经年
执笔经年 2021-02-03 20:30

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

temporary         


        
2条回答
  •  佛祖请我去吃肉
    2021-02-03 20:41

    You can extract some of the logic into separate functions, and return the inner promises to bubble up any exceptions to 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}
      });
    }
    

提交回复
热议问题