【发布时间】:2021-11-27 03:41:00
【问题描述】:
我有这个脚本似乎没有运行。我在变量重新分配方面注意到了这一点。显示代码片段和输出
//Create New Open Market under the game
let latestRowId = 1;
var sqlQuery2 = "SELECT ID FROM markets ORDER BY LAST_EDITED DESC LIMIT 1";
db.query(sqlQuery2, [], function(err, result4) {
if (err){
console.log("Error during /openBetoBetoMarket. Proc_4" + err);
res.status(500).json({ msg: "Server Error /openBetoBetoMarket. gameID:" + gameID });
} else {
console.log("result4", result4[0].ID)
latestRowId = result4[0].ID
}
});
console.log("latest_row_id", latestRowId);
newRowID = latestRowId + 1
newMarketId = result[0].MARKET_ID + 1
newGameId = gameID
newDescription = gameTitle
console.log("New row id", newRowID, "new market id", newMarketId)
sqlQuery = "INSERT INTO markets (ID, MARKET_ID, GAME_ID, DESCRIPTION, LAST_EDITED, WRITER) VALUES (?, ?, ?, ?, NOW(), CURRENT_USER);"
db.query(sqlQuery, [newRowID, newMarketId, newGameId, newDescription], (err, result4) => {
if (err){
console.log("Error during /openBetoBetoMarket. Proc_5 " + err);
res.status(500).json({ msg: "Server Error /openBetoBetoMarket. gameID:" + gameID });
} else if (result4.affectedRows > 0){
console.log("Created new open market for /openBetoBetoMarket. MarketID: " + newMarketId);
res.status(200).json({msg: "Created New Open Market", marketID: newMarketId, isOpen: 1})
} else {
console.log("Error during /openBetoBetoMarket. Proc_5. Inserted but no affected Rows");
res.status(500).json({ msg: "Server Error /openBetoBetoMarket. gameID:" + gameID });
}
})
输出如下:
latest_row_id 1
新行 id 2 新市场 id 3
结果4 2
/openBetoBetoMarket 期间出错。 Proc_5 错误:ER_DUP_ENTRY:键“markets.PRIMARY”的重复条目“2”
如您所见,它似乎跳过了第一个 db.query 并直接进入下一个变量赋值,然后执行第一个 db.query。知道我在这里缺少什么吗?第一次在这里发帖。谢谢
【问题讨论】:
-
我建议搜索“非阻塞异步 Javascript”并阅读。这里的关键是
db.query()是非阻塞的。它在调用它的回调之前返回,它会在稍后的某个时间调用它的回调,在其他代码执行之后很久。这是 Javascript 中非阻塞、异步 I/O 的关键和基本原则,学习和理解很重要。
标签: javascript mysql node.js express