【问题标题】:NodeJS and MYSQL IssueNodeJS 和 MYSQL 问题
【发布时间】:2018-01-31 21:11:27
【问题描述】:

我的代码应该检索用户 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;
 

【问题讨论】:

    标签: mysql node.js


    【解决方案1】:

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

    【讨论】:

    • 它只是稍后在我的代码中给我一个错误“unexpected });”
    • 我更新了答案,缺少一个大括号来关闭函数decrementDrop,你能再试一次吗?
    猜你喜欢
    • 2018-12-13
    • 2017-10-07
    • 1970-01-01
    • 2019-03-03
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    相关资源
    最近更新 更多