Are nested catches within promises required?

前端 未结 2 2047
执笔经年
执笔经年 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:39

    No, they won't. They only bubble up to the result promise if you chain your promises, for which you need to return the inner promises created by the callbacks. Otherwise the outer promise cannot wait for them and will not know when/how they resolve (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));
    

提交回复
热议问题