在承诺中是否需要嵌套捕获? [英] Are nested catches within promises required?

查看:57
本文介绍了在承诺中是否需要嵌套捕获?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们希望减少诺言中的陷阱数量.如果我们删除嵌套的渔获量,异常会上升到父渔获量吗?

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?

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'd like to remove the two nested catches and keep only the catch at the bottom. Is this ok?

推荐答案

不,他们不会.如果您您的诺言,它们只会冒泡到结果诺言,为此您需要return回调创建的内部诺言.否则,外部承诺不能等待他们,也不会知道他们何时/如何解决(他们是否实现或拒绝).

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));

这篇关于在承诺中是否需要嵌套捕获?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆