我试图将回调更新查询转换为一个漂亮,整洁的承诺..然后它击中了我。我需要承诺吗?
这是我以前的旧回调函数:
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);
});
这确实有效,但它是好的"作为承诺?承诺是否适用于更新/插入查询?下面的函数没有工作,没有错误,这让我想知道promises是否用于更新数据库数据或只是选择它?或者我的功能是否被破坏但是没有错误?
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
});
});
答案 0 :(得分: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"
。也就是说,你的回调版本开始时是不正确的。