如何避免巨大的嵌套if else

时间:2017-04-25 14:28:25

标签: javascript node.js hapijs

这是我登录的代码

method: 'POST',
        path: '/api/login/sp',
        config: { auth: false },
        handler: function (request, reply) {
            User.findOne({ phone: request.payload.phone }, function (err, user) {
                if (err) throw err;
                if (user !== null) {
                    user.comparePassword(request.payload.password, function (err, isMatch) {
                        if (err) throw err;
                        if (isMatch) { // Login success
                            data = {
                                "statusCode": 200,
                                "token": generateJWT(user._id)
                            }
                            return reply(data);
                        }
                        else {
                            reply(Boom.unauthorized('Invalid Account'))
                        }
                    });
                }
                else { // Invalid User
                    reply(Boom.unauthorized('Invalid Account'))
                }
            });
        }

需要大量代码并且很难阅读。有没有办法更好地编写这部分代码,以便它易于维护和读取?

2 个答案:

答案 0 :(得分:1)

您可以使用return reply()

User.findOne({phone: request.payload.phone}, function (err, user) {
    if (err) throw err;
    if (user === null) return reply(Boom.unauthorized('Invalid Account'));
    user.comparePassword(request.payload.password, function (err, isMatch) {
        if (err) throw err;
        if (!isMatch) return reply(Boom.unauthorized('Invalid Account'));
        data = {
            "statusCode": 200,
            "token": generateJWT(user._id)
        };
        return reply(data);
    });
})

答案 1 :(得分:0)

尝试使用返回早期模式:Return early pattern for functions

User.findOne(..., {
    // generic error
    if (err) throw err;

    // invalid user
    if (user === null) {
        reply(Boom.unauthorized('Invalid Account'));
        return;
    }

    user.comparePassword(..., {
        if (err) throw err;

        if (!isMatch) {
            reply(Boom.unauthorized('Invalid Account'));
            return;
        }

        data = {
            "statusCode": 200,
            "token": generateJWT(user._id)
        };
        reply(data);
    });
});