否则如何避免巨大的嵌套
How to do avoid huge nested if else
这是我的登录代码
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'))
}
});
}
它需要大量代码并且很难阅读。有没有办法更好地编写这部分代码,使其易于维护和阅读?
您可以使用 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);
});
})
尝试使用 return 早期模式: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);
});
});
这是我的登录代码
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'))
}
});
}
它需要大量代码并且很难阅读。有没有办法更好地编写这部分代码,使其易于维护和阅读?
您可以使用 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);
});
})
尝试使用 return 早期模式: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);
});
});