添加连接池后代码 运行 顺序错误(需要 async/await?)
Code running in wrong order after added connection pool (async/await needed?)
我有一个 NodeJS API,它正在使用 'normal connections' 到 MYSQL 数据库并且 运行 好吧,我遇到了断开连接问题。
我现在已经实现了池化,它正在工作,但是由于连接的新性质,现在似乎有些代码 运行 乱序了。
我从未使用过 async/await,因为我对编码还很陌生,但我已尝试在此处进行编码以获得所需的响应。
我几乎已经在控制台日志中查看它的顺序 运行 而不是得到“1,2,3”,我得到的是“2,3,1”,这显然会给我错误的结果,因为我需要在继续之前获取查询数据。
有人可以展示如何让这个等待系统工作吗?
第一部分从用户那里获取 MAC 和 ID,然后检查它是否已经存在于我的数据库中。如果是,则更新最近登录的日期时间。如果没有,则添加 MAC.
问题是我没有收到关于 mac 是否存在的回复,所以它始终为“假”,因此 mac 不断被添加,因为它不存在等待第一个查询结果!
router.post('/updateComp/',verify,async (req,res) => {
//console.log(req.params.MAC)
var sqlString = "SET @chemistID = ?; SET @MAC = ?; Call checkMAC(@chemistID,@MAC)";
try{
const MAC = req.body.MAC;;
const compName = req.body.compName;
var compCount = 0;
var MACExists = false;
console.log(MAC + " " + compName);
await connection.query(sqlString,[req.user._id,MAC], (err,rows,fields)=>{
console.log("Check 1");
if(!err){
rows.forEach(element => {
if(element.constructor == Array){
compCount = element[0].compCount;
MACExists = element[0].MACExists;
console.log(compCount);
console.log(MACExists);
}
else{
//array not returned?
return res.status(500);
}
})
}else{
//sql con error?
return res.status(500);
}
console.log("comcount = " + compCount);
})
console.log("Check 2");
if(compCount == 0 || (compCount < 7 && MACExists == false)){
//Insert new comp
var sqlString = "INSERT INTO tblLicense (chemistID,compName,MAC,lastAccess) VALUES (?,?,?,current_timestamp());";
console.log("Check 3");
connection.query(sqlString,[req.user._id,compName,MAC], (err,rows,fields)=>{
if(!err){
console.log("New terminal added for " + req.user._id);
return res.status(200).json({
Result: true,
compAdded: true
})
}else{
console.log("Failed to add new computer to sub " + req.user._id);
return res.status(500).json({
Result: false,
compAdded: false,
Comment: "Failed to add new computer to sub"
})
}
})
}else{
if (compCount == 7){
if(MACExists){
return res.status(200).json({
Result: true
})
}else{
return res.status(200).json({
Result: false,
compAdded: false,
Comment: compCount
})
}
}else{
//Update time of current comp access
var sqlString = "UPDATE tblLicense SET lastAccess = current_timestamp() WHERE MAC = ? AND chemistID = ?;";
connection.query(sqlString,[MAC,req.user._id], (err,rows,fields)=>{
if(!err){
return res.status(200).json({
Result: true,
compAdded: false
})
}
else
{
return res.status(500).json({
Result: false,
compAdded: false
})
}
})
}
}
} catch (e) {
// this catches any exception in this scope or await rejection
console.log(e);
res.status(500).json({ Result: e });
}
});
连接配置:
const mysql = require('mysql');
var pool = mysql.createPool({
host:'localhost',
user: '1234',
password: '1234',
database : '1234',
multipleStatements: true,
connectionLimit: 10
});
pool.getConnection((err, connection) => {
if (err) {
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
console.error('Database connection was closed.')
}
if (err.code === 'ER_CON_COUNT_ERROR') {
console.error('Database has too many connections.')
}
if (err.code === 'ECONNREFUSED') {
console.error('Database connection was refused.')
}
}
if (connection) connection.release()
return
})
module.exports ={
connection : pool
}
检查 https://github.com/mysqljs/mysql 似乎 connection.query
从来没有 returns 一个承诺。
您仍然可以通过将 connection.query
包装在 promise 中来使用 async/await。
这里有一个 post 解释了如何做 https://medium.com/wenchin-rolls-around/example-of-using-transactions-with-async-await-via-mysql-connection-pool-9a37092f226f
看起来另一种选择是使用 Bluebird
我有一个 NodeJS API,它正在使用 'normal connections' 到 MYSQL 数据库并且 运行 好吧,我遇到了断开连接问题。 我现在已经实现了池化,它正在工作,但是由于连接的新性质,现在似乎有些代码 运行 乱序了。
我从未使用过 async/await,因为我对编码还很陌生,但我已尝试在此处进行编码以获得所需的响应。 我几乎已经在控制台日志中查看它的顺序 运行 而不是得到“1,2,3”,我得到的是“2,3,1”,这显然会给我错误的结果,因为我需要在继续之前获取查询数据。
有人可以展示如何让这个等待系统工作吗? 第一部分从用户那里获取 MAC 和 ID,然后检查它是否已经存在于我的数据库中。如果是,则更新最近登录的日期时间。如果没有,则添加 MAC.
问题是我没有收到关于 mac 是否存在的回复,所以它始终为“假”,因此 mac 不断被添加,因为它不存在等待第一个查询结果!
router.post('/updateComp/',verify,async (req,res) => {
//console.log(req.params.MAC)
var sqlString = "SET @chemistID = ?; SET @MAC = ?; Call checkMAC(@chemistID,@MAC)";
try{
const MAC = req.body.MAC;;
const compName = req.body.compName;
var compCount = 0;
var MACExists = false;
console.log(MAC + " " + compName);
await connection.query(sqlString,[req.user._id,MAC], (err,rows,fields)=>{
console.log("Check 1");
if(!err){
rows.forEach(element => {
if(element.constructor == Array){
compCount = element[0].compCount;
MACExists = element[0].MACExists;
console.log(compCount);
console.log(MACExists);
}
else{
//array not returned?
return res.status(500);
}
})
}else{
//sql con error?
return res.status(500);
}
console.log("comcount = " + compCount);
})
console.log("Check 2");
if(compCount == 0 || (compCount < 7 && MACExists == false)){
//Insert new comp
var sqlString = "INSERT INTO tblLicense (chemistID,compName,MAC,lastAccess) VALUES (?,?,?,current_timestamp());";
console.log("Check 3");
connection.query(sqlString,[req.user._id,compName,MAC], (err,rows,fields)=>{
if(!err){
console.log("New terminal added for " + req.user._id);
return res.status(200).json({
Result: true,
compAdded: true
})
}else{
console.log("Failed to add new computer to sub " + req.user._id);
return res.status(500).json({
Result: false,
compAdded: false,
Comment: "Failed to add new computer to sub"
})
}
})
}else{
if (compCount == 7){
if(MACExists){
return res.status(200).json({
Result: true
})
}else{
return res.status(200).json({
Result: false,
compAdded: false,
Comment: compCount
})
}
}else{
//Update time of current comp access
var sqlString = "UPDATE tblLicense SET lastAccess = current_timestamp() WHERE MAC = ? AND chemistID = ?;";
connection.query(sqlString,[MAC,req.user._id], (err,rows,fields)=>{
if(!err){
return res.status(200).json({
Result: true,
compAdded: false
})
}
else
{
return res.status(500).json({
Result: false,
compAdded: false
})
}
})
}
}
} catch (e) {
// this catches any exception in this scope or await rejection
console.log(e);
res.status(500).json({ Result: e });
}
});
连接配置:
const mysql = require('mysql');
var pool = mysql.createPool({
host:'localhost',
user: '1234',
password: '1234',
database : '1234',
multipleStatements: true,
connectionLimit: 10
});
pool.getConnection((err, connection) => {
if (err) {
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
console.error('Database connection was closed.')
}
if (err.code === 'ER_CON_COUNT_ERROR') {
console.error('Database has too many connections.')
}
if (err.code === 'ECONNREFUSED') {
console.error('Database connection was refused.')
}
}
if (connection) connection.release()
return
})
module.exports ={
connection : pool
}
检查 https://github.com/mysqljs/mysql 似乎 connection.query
从来没有 returns 一个承诺。
您仍然可以通过将 connection.query
包装在 promise 中来使用 async/await。
这里有一个 post 解释了如何做 https://medium.com/wenchin-rolls-around/example-of-using-transactions-with-async-await-via-mysql-connection-pool-9a37092f226f
看起来另一种选择是使用 Bluebird