我正在尝试创建一个函数,该函数返回玩家基于本地数据库获得的胜利数量。然而,值'p1'和'p2'似乎每次退出循环时都会重置为0.
function getAmountOfWins(player) {
var p1 = 0, p2 = 0;
db.transaction(function (tx) {
tx.executeSql("SELECT * FROM Filter WHERE player1='" + player + "'", [], function (tx, results) {
for (var i = 0; i < results.rows.length; i++) {
current = results.rows.item(i);
p1 = p1 + current.p1wins;
}
});
});
db.transaction(function (tx) {
tx.executeSql("SELECT * FROM Filter WHERE player2='" + player + "'", [], function (tx, results) {
for (var i = 0; i < results.rows.length; i++) {
current = results.rows.item(i);
p2 = p2 + current.p2wins;
}
});
});
console.log("Total Wins before return: " + (p1 + p2));
return p1 + p2;
}
在这种情况下,当p1和p2退出'db.transaction'时,它们似乎被重置为0。我很遗憾如何保存数据,所以我可以实际返回它。
任何人都有一个可以防止这种情况的魔法修复?
答案 0 :(得分:2)
他们没有重置。他们从未被设定过。 executeSQL
和transaction
方法是异步。这意味着你必须做一些这样的事情:
function getAmountOfWins(player, callback) {
// Call function, callback is executed after the query calculations
getPlayerValues(1, player, function(p1num){
// Call function, callback is executed after the query calculations
getPlayerValues(2, player, function(p2num){
// Call the original callback function
callback( p1num + p2num );
});
});
}
// Get the player values
function getPlayerValues(playernr, player, callback){
db.transaction(function (tx) {
tx.executeSql("SELECT * FROM Filter WHERE player" + playernr + "='" + player + "'", [], function (tx, results) {
var p = 0;
for (var i = 0; i < results.rows.length; i++) {
current = results.rows.item(i);
p = p + current.p2wins;
}
callback(p);
});
});
}
电话:
// Get the amount of wins, this is an async functionm with the callback
getAmountOfWins(player, function(value){
console.log("Total Wins before return: " + (value));
});
答案 1 :(得分:0)
我将假设executeSql
是异步的,因为它接受回调函数。
您执行此功能的主体将在console.log
运行很久之后的某个时间点执行。您需要重构代码,以便通过传递给console.log
的回调运行executeSql
(以及您想要包含的任何其他逻辑)。