问题描述
Node.js express框架的一个get请求接口,具体操作是从数据库中检索验证码,如果正确就往另一个数据表中写入数据
原始代码:
app.get('/mailconfirm', function (req, res) {
const mail = req.query.mail;
const cap = req.query.cap;
var findmailsql = "SELECT * FROM CAP WHERE MAIL='" + mail + "'";
connection.query(findmailsql, function (err, result) {
if (err) {
console.log('[INSERT ERROR] - ', err.message);
return;
}
if (result == 0) {
res.send(eval('(' + '{"status":300,"msg":"NO EMAIL"}' + ')'));
} else {
let FindCapSql = "SELECT * FROM `CAP` WHERE MAIL='"+mail+"' AND CAP="+cap;
//= eval('(' + '{"status":300,"msg":"CAP FALSE"}' + ')');
connection.query(FindCapSql, function(err, result){
if (err) {
console.log('[INSERT ERROR] - ', err.message);
return;
}
if(result == 0){
res.send(eval('(' + '{"status":300,"msg":"CAP FALSE"}' + ')'));
} else {
console.log(result);
let insertEmailSql = 'UPDATE USERS SET MAIL = ? WHERE USER_ID = ?';
let insertEmailSqlValue = [mail, result.USER_ID];
connection.query(insertEmailSql, insertEmailSqlValue, function (err, result) {
if (err) {
console.log('[UPDATE ERROR] - ', err.message);
return;
}
console.log('test');
ret = result;
res.send(ret);
return;
})
}
})
/*
for (let i = 0; i < result.length; i++) {
if (result[i].CAP == cap) {
let insertEmailSql = 'UPDATE USERS SET MAIL = ? WHERE USER_ID = ?';
let insertEmailSqlValue = [mail, result[i].USER_ID];
connection.query(insertEmailSql, insertEmailSqlValue, function (err, result) {
if (err) {
console.log('[UPDATE ERROR] - ', err.message);
return;
}
console.log('test');
ret = result;
res.send(ret);
return;
})
}
}
console.log('test2');
//console.log(result.length);*/
}
//res.send(ret);
})
})
上面这段是修改后的代码,问题复现的结构大致如下:
for(let i=0; i<10; i++){
if(result[i] === 'test'){
connection.query(sql, function(err, result){
console.log('1');
})
}
}
console.log('2');
上述代码运行以后在进入for以后,由于mysql请求是异步请求,执行的时候控制台输出'2'会比mysql请求后输出‘1’提前执行,控制台会先输出2再输出1