I currently working on a hybrid App for organize soccer tournaments. The data for a new tournament is collected in a object like this:
var tournamentSettingsObj = {
gameDuration: 2,
groups: 1,
groupsBool: true,
koBool: false,
name: "My Tournament",
size: 3,
teams: [
{
name: "Team 1",
number: 1,
players: [
{
name: "Player 1 - 1",
playerNumber: 1
},
{
name: "Player 2 - 1",
playerNumber: 2
},
{
name: "Player 3 - 1",
playerNumber: 3
}
]
},
{
name: "Team 2",
number: 2,
players: [
{
name: "Player 1 - 2",
playerNumber: 1
},
{
name: "Player 2 - 2",
playerNumber: 2
}
]
},
{
name: "Team 3",
number: 3,
players: [
{
name: "Player 1 - 3",
playerNumber: 1
},
{
name: "Player 2 - 3",
playerNumber: 2
}
]
}
],
teamsInGroup: 3,
type: 1
}
I want to put this data in a sqlite database. When opening the database, i've a webSQL-fallback for developing locally in my browser...
if($cordovaSQLite && $window.sqlitePlugin !== undefined){
db = $window.sqlitePlugin.openDatabase({name: "mydb.db"});
} else {
db = $window.openDatabase("mydb.db", "1.0", "mydb.db", 200000);
}
My problem is that i have to make nested loops to insert the tournament, the group(s), the teams for each group and the players of each team. In my opinion the only possible way to do this was to put the transactions into nested loops.
I know that these transactions are asynchronous. My solution below would only work if everything would be synchronous. I tried to solve this with callbacks and make it synchronous, but i always doesn't work. (Maybe because there are 3 loops and not only one...)
What's the best way to solve these asynchronous nested looping? Is there any other solution, maybe on the sql side?
db.transaction(function(tx) {
tx.executeSql("...", items_tournaments, function(tx, res){
var teamIndex = 0;
// Insert Groups
for (var i=0;i<tournamentSettingsObj.groups;i++){
tx.executeSql("...", [tournamentSettingsObj.teamsInGroup, res.insertId], function(res2) {
// Insert Teams
for (var j=0;j<tournamentSettingsObj.teamsInGroup;j++){
tx.executeSql("...", [tournamentSettingsObj.teams[teamIndex].name, res2.insertId, res.insertId], function(res3) {
// Insert Players
for (var k=0;k<tournamentSettingsObj.teams[teamIndex].players.length;k++){
tx.executeSql("...", [tournamentSettingsObj.teams[teamIndex].players[k].name, res3.insertId], function(res4) {
// Last insert - all complete
if ((teamIndex >= tournamentSettingsObj.size - 1) && (k >= tournamentSettingsObj.teams[teamIndex].players.length - 1)){
console.log("Complete");
}
});
}
});
teamIndex++;
}
});
}
});
});
Aucun commentaire:
Enregistrer un commentaire