有条件地在一系列承诺中尽早退出而不会产生错误

时间:2016-07-29 22:02:08

标签: javascript node.js promise

在我的节点js app中,我尝试创建一个需要几个异步步骤的注册路由。在早期的步骤中,我想要停止并返回一条消息,但我对将条件混合到承诺中感到困惑。

我的具体问题是以下伪代码中的注释:

router.post('/register', function(req, res, next) {
    var identity = req.body.identity;
    var password = req.body.password;

    // can't register without a reservation
    hasReservation(identity).then(function(hasReservation) {
        if (hasReservation) { return register(identity, password); }
        else {
            // stuck here: I want to say:
            res.json({ registered: false, reason: "missing reservation" });
            // and then I want to stop further promises
            // but this isn't an error, I don't want to throw an error here
        }
    }).then(function(user) {
        // in my app, registering an existing user is okay
        // I just want to reset a few things about the user and save
        // but I don't want to be here if there's no reservation
        if (user) {
            user.foo = 'bar';
            return user.save().then(function() { return user; });
        } else {
            return register(identity, password);
        }
    }).then(function(user) {
        // I want to do more asynch stuff here
    }).then(function(result) {
        res.json(result);
    }).catch(function(error) {
        res.status(500).json(error);
    });
});

我如何有条件地"拯救"在第一个承诺完成之后,没有抛出错误?

1 个答案:

答案 0 :(得分:4)

如果register(identity,password)返回一个promise,您可以按如下方式重新组织代码:

router.post('/register', function(req, res, next) {
    var identity = req.body.identity;
    var password = req.body.password;

    // can't register without a reservation
    hasReservation(identity)
    .then(function(hasReservation) {
        if (hasReservation) { 
            return register(identity, password)
            .then(function(user) {
                // in my app, registering an existing user is okay
                // I just want to reset a few things about the user and save
                // but I don't want to be here if there's no reservation
                if (user) {
                    user.foo = 'bar';
                    return user.save().then(function() { return user; });
                } else {
                    return register(identity, password);
                }
            })
            .then(function(user) {
                // I want to do more asynch stuff here
            })
            .then(function(result) {
                res.json(result);
            })
        } else {
            // stuck here: I want to say:
            res.json({ registered: false, reason: "missing reservation" });
            // and then I want to stop further promises
            // but this isn't an error, I don't want to throw an error here
        }
    })
    .catch(function(error) {
        res.status(500).json(error);
    });
});

否则,如果register(..)只返回一个值,则将寄存器的第一个实例(...)包装在Promise.resolve中

        return Promise.resolve(register(identity, password))