我的代码应该检索" DropsRemaining"用户ID(它成功),然后从它检索的数字-1。当检索数据时,它返回该字符串" [RowDataPacket {DropsRemaining:5}}"但是,DropsRemaining中的代码结尾不是-1,而是将DropsRemaining设置为-1。如果有人可以帮忙解决这个问题,我真的很感激。
var sql = "SELECT DropsRemaining FROM UserData WHERE DiscordID LIKE " + message.author.id;
var DropCount = [];
connection.query(sql, function (err, result) {
if (!err)
setValue(result);
else
console.log("No Information For That User Found");
});
function setValue(value) {
DropCount = value;
console.log(DropCount);
};
//Remove drop from user
DropCount = DropCount - 1;
var sql = "UPDATE UserData SET DropsRemaining = " + DropCount + " WHERE DiscordID = " + message.author.id;

答案 0 :(得分:0)
问题是你编写Javascript代码的顺序并不完全是它最终的执行方式。
当您调用connection.query()
函数时,下一行代码不一定已经具有该函数的结果。
我建议你看看这个book series,他们对这些特征有很好的解释。
以下代码可能会输出预期的响应。请注意,我嵌套了代码,因此我可以正确控制流程。
var sql = "SELECT DropsRemaining FROM UserData WHERE DiscordID LIKE " + message.author.id;
// Get the DropsRemaining
connection.query(sql, function (err, result) {
if (!err) {
// No errors in the query, decrement the Drops
decrementDrop(result);
} else {
console.log("No Information For That User Found");
}
});
function decrementDrop(dropsAvailable) {
var dropsRemaining = dropsAvailable - 1;
var updateSql = "UPDATE UserData SET DropsRemaining = " + dropsRemaining + " WHERE DiscordID = " + message.author.id;
// Update the DropsRemaining column to the dropsRemaining, i.e., decrement the DropsRemaining column value
connection.query(updateSql, function (err, result) {
if (!err) {
console.log("DiscordID = " + message.author.id +" has " + dropsRemaining + " drops remaining")
} else {
console.log("Error!");
}
});
}