需要帮助来了解mysql查询的异步/承诺

时间:2018-07-03 20:44:53

标签: mysql node.js

var mysql = require('mysql');

var con = mysql.createConnection({
    host: "host",
    user: "login",
    password: "password",
    database: "db"
});

con.connect(function (err) {
    if (err) throw err;
    console.log("Connected!");

    function addTalentPoint(id,amount){
        var sql = "SELECT RegValue FROM `Registry` WHERE RegChaId="+id+" AND RegIdentifier='TalentPoints'"

        var endingTalentPoint = 0;

        con.query(sql, function (err, result) {
            if (err) throw err;
            console.log("Starting Talent Point: "+result[0].RegValue);
            endingTalentPoint = result[0].RegValue + amount

            var sql = "UPDATE `Registry` SET RegValue="+endingTalentPoint+" WHERE RegChaId="+id+" AND RegIdentifier='TalentPoints'"
            con.query(sql, function (err, result) {
            if (err) throw err;
                console.log(endingTalentPoint)
            });
        });


    }
    function getTalentPoint(id){
        var sql = "SELECT RegValue FROM `Registry` WHERE RegChaId="+id+" AND RegIdentifier='TalentPoints'"

        con.query(sql, function (err, result) {
            if (err) throw err;
            console.log("get talent point: "+result[0].RegValue);
        });
    }

    addTalentPoint(4,5)
    getTalentPoint(4)
});

我的示例输出:

  

起始人才点:125

     

获得天赋点:125

     

130

我已经阅读了许多博客,并尝试使用async / await和设置Promise,但是我没有找到所需的位置。我正在尝试让代码等待addTalentPoint完成,然后再执行getTalentPoint。它是野兽的本质,它发出查询,然后继续执行代码?我可以将getTalentPoint放在UPDATE下的回调中,但是我怎么知道更新已完成?

1 个答案:

答案 0 :(得分:-1)

addTalentPoint仍在执行异步操作-所有这些con.query调用都是异步操作-因此,除非您在回调中进行工作,否则事情将立即执行(例如您的getTalentPoint函数)-一种解决方案是在addTalentPoint函数中添加回调函数。看到以下变化:

//First, add a callback parameter
function addTalentPoint(id,amount,callback){
    ...
    //next, use this callback when the work is done
    if (err) throw err;
    console.log(endingTalentPoint)
    if (callback) callback(); //if a callback exists, call it

现在,使用您的新参数:

addTalentPoint(4,5, function() {
    //All done doing the work in addTalentPoint, lets do more things now!
    getTalentPoint(4)
})