刚刚开始接触node,现在在写短信验证码的功能,但是在操作数据库的时候我发现每个异步函数都有一个err,这个err我觉得是应该不会出现的,但是免不了可能会出现,所以每个都要判断吗?而且在里面是做什么操作呢?而且我现在这样写下去,代码嵌套的特别厉害。。。求各位大哥给点思路和指导 代码如下: 1、client是redis实例化出来的
// 验证短信验证码
exports.verifyCode = function (req, res) {
// 获取用户传递的手机号和验证码
let phone = req.query.phone;
let upCode = req.query.code;
if (client.get(phone)) {
client.get(phone, function (err, msgCode) {
if (upCode == msgCode) {
// 从连接池获取连接
pool.getConnection(function (err, connection) {
// 获取前台页面传过来的参数
var param = req.query || req.params;
// 检查数据库是否有手机号
connection.query(userSQL.getIdByMobile, param.phone, function (err, result) {
if (err) {
res.send(jsonTool.send_json(-1, '注册失败', ''));
} else {
if (result.length != 0) { // 不为0,说明之前注册过,直接返回之前的user_id
res.send(jsonTool.send_json(0, '登录成功', result[0].user_id.toString()));
} else { // 为0,添加用户
connection.query(userSQL.insertMobile, param.phone, function (err, result) {
if (err) throw err;
// 添加成功并返回给前端
connection.query(userSQL.getIdByMobile, param.phone, function (err, result) {
if (result.length != 0) {
res.send(jsonTool.send_json(0, '注册成功', result[0].user_id.toString()));
} else {
res.send(jsonTool.send_json(-1, '注册失败', ''));
}
});
});
}
}
// 释放连接
connection.release();
});
});
} else {
res.send(jsonTool.send_json(-1, '验证码错误', ''));
}
});
} else {
res.send(jsonTool.send_json(-1, '验证码已过期', ''));
}
}