How to use aysnc module in node.js to loop over two arrays -
i want loop on array , write info database. code below shows how in non-async way loop. know not preferred way of doing it.
for(var x = 0;x < tt.matches.length;x++) //match each player match , playerid 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 need perform following, 1 time again shown in '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 keeping counter of open db calls, calling next phase of programme when of calls have returned. see below.
there's theoretical hole in approach though, if of player.update()
calls homecoming before process.nexttick completion status may triggered early.
var activecalls = 0; for(var x = 0;x < tt.matches.length;x++) //match each player match , playerid 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++; } }
arrays node.js asynchronous
No comments:
Post a Comment