我的代码应该检索用户ID的“ DropsRemaining”(成功完成),然后从检索到的数字中返回-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;
 

最佳答案

问题在于您编写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!");
            }
        });
    }

10-07 21:10