I want to loop over an array and then write some data to the database. The code below shows how I would do it in a non-async way with a for loop. I know this is not the preferred way of doing it.
for(var x = 0;x < tt.matches.length;x++) //Match each player with a match and a playerId from the tournament tree
{
if(tt.matches[x].p[0] !== -1)
{
var tmId = JSON.stringify(tt.matches[x].id);
Player.update({ _id : grUpd.players[y] },{ tournamentMatchId : tmId, treeId : tt.matches[x].p[0], opponent : tt.matches[x].p[1] },{ safe : true }, function (err) {
if(err)
{
console.log(err);
}
});
y++;
}
if(tt.matches[x].p[0] === -1)
{
byes++;
}
if(tt.matches[x].p[1] !== -1)
{
var tmId = JSON.stringify(tt.matches[x].id);
Player.update({ _id : grUpd.players[y] },{ tournamentMatchId : tmId, treeId : tt.matches[x].p[1], opponent : tt.matches[x].p[0] },{ safe : true }, function (err) {
if(err)
{
console.log(err);
}
});
y++;
}
if(tt.matches[x].p[1] === -1)
{
byes++;
}
}
I then need to perform the following, again shown in a 'traditional way'.
for(var x = 0;x < plyrs.length;x++)
{
var nextMatch = JSON.stringify(tt.upcoming(plyrs[x].treeId)) ;
Player.update({ _id : plyrs[x]._id },{ tournamentMatchId : nextMatch },{ safe : true }, function (err) {
if(err)
{
console.log(err);
}
});
}
You could do it by keeping a counter of open DB calls, then calling the next phase of your program when all of the calls have returned. See below.
There's a theoretical hole in this approach though, which is that if any of your Player.update() calls return before process.nextTick then the completion condition may be triggered early.
var activeCalls = 0;
for(var x = 0;x < tt.matches.length;x++) //Match each player with a match and a playerId from the tournament tree
{
if(tt.matches[x].p[0] !== -1)
{
var tmId = JSON.stringify(tt.matches[x].id);
activeCalls++;
Player.update({ _id : grUpd.players[y] },{ tournamentMatchId : tmId, treeId : tt.matches[x].p[0], opponent : tt.matches[x].p[1] },{ safe : true }, function (err) {
activeCalls--;
if(err)
{
console.log(err);
}
if ( activeCalls == 0 ) doNextThing()
});
y++;
}
if(tt.matches[x].p[0] === -1)
{
byes++;
}
if(tt.matches[x].p[1] !== -1)
{
var tmId = JSON.stringify(tt.matches[x].id);
activeCalls++;
Player.update({ _id : grUpd.players[y] },{ tournamentMatchId : tmId, treeId : tt.matches[x].p[1], opponent : tt.matches[x].p[0] },{ safe : true }, function (err) {
activeCalls--;
if(err)
{
console.log(err);
}
if ( activeCalls == 0 ) doNextThing()
});
y++;
}
if(tt.matches[x].p[1] === -1)
{
byes++;
}
}