문제

I'm trying to convert a callback update query into a nice, neat promise.. but then it hit me. Do I need to promise it at all?

Here's my old, callback function:

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);
});

This works, sure, but is it "as good" as a promise? Do promises work for update/insert queries? The function below isn't working, with no error, which is making me wonder if promises are of use for updating database data or just selecting it? Or is my function just broken but not error broken?

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
    });
});
도움이 되었습니까?

해결책

Promises work beautifully for updates.

Your functions are not the same:

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);
});

I'll note again, you continue the handling even if there was an error, and emit "talk" without waiting for the query. That is, your callback version was incorrect to begin with.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top