1

我正在尝试将回调更新查询转换为一个不错的、简洁的承诺……但后来它击中了我。我需要承诺吗?

这是我的旧回调函数:

con.getConnection(function(err,connection){
    if (err) console.log("Get Connection Error.. "+err);
    con.query("UPDATE player_data SET x="+mysql.escape(x)+", y="+mysql.escape(y)+" WHERE id="+mysql.escape(this.id),function(err) {
        if (err) console.log(err);
        this.x = x;
        this.y = y;
        connection.release();
    });
    req.io.emit("talk", {x:req.data.x,y:req.data.y});
    console.log(this.x,this.y);
});

这确实有效,但它和承诺一样“好”吗?承诺是否适用于更新/插入查询?下面的函数不起作用,没有错误,这让我想知道 promise 是用于更新数据库数据还是只是选择它?还是我的功能刚刚损坏但没有错误损坏?

con.getConnectionAsync().then(function(connection) {
    console.log(x,y,this.id) //params sent in. x/y change often, but id = 9. My console shows the values
    connection.queryAsync("UPDATE player_data SET x="+mysql.escape(x)+", y="+mysql.escape(y)+" WHERE id="+mysql.escape(this.id)) //does not update db!
    .finally(function() {
        this.x = x; //this.x logs x
        this.y = y; //same with y
        req.io.emit("talk", {x:this.x,y:this.y});
            //the socket is logged on another page, logs the same data as above.
        connection.release();
        console.log(this.x,this.y); //still logs
    });
});
4

1 回答 1

1

Promise 非常适合更新。

你的功能不一样:

con.getConnection(function(err,connection){
    if (err) console.log("Get Connection Error.. "+err);
    con.query("UPDATE player_data SET x="+mysql.escape(x)+", y="+mysql.escape(y)+" WHERE id="+mysql.escape(this.id),function(err) {
        if (err) console.log(err);
        // continue even if error!

        connection.release();
    });
    req.io.emit("talk", {x:req.data.x,y:req.data.y}); // <- Emit before query
    console.log(this.x,this.y);
});

我会再次注意,即使出现错误,您也会继续处理,并且"talk"无需等待查询就发出。也就是说,您的回调版本一开始就不正确。

于 2014-03-27T20:41:29.840 回答