const divisions = [
{
_id: 0,
name: 'First division',
teams: [
{
name: 'Team A',
players: [
'John',
'Jim',
'Tom',
'Jacob'
]
},
{
name: 'Team B',
players: [
'John',
'Jim',
'Tom',
'Jacob'
]
}
],
players: [],
tournament: false
},
{
_id: 1,
name: 'Second division',
teams: [
{
name: 'Team A',
players: [
'John',
'Jim',
'Tom',
'Jacob'
]
},
{
name: 'Team B',
players: [
'John',
'Jim',
'Tom',
'Jacob'
]
}
],
players: [],
tournament: false
},
{
_id: 2,
name: 'Third division',
teams: [
{
name: 'Team A',
players: [
'John',
'Jim',
'Tom',
'Jacob'
]
},
{
name: 'Team B',
players: [
'John',
'Jim',
'Tom',
'Jacob'
]
}
],
players: [],
tournament: false
}
]
calcTournamentStats = (player, division_id, callback) => {
setTimeout(() => {
callback(null, 'Anthony');
}, 2000);
}
calcStats = (team, division_id, callback) => {
setTimeout(() => {
callback(null, 'Team F');
}, 2000);
}
getDivisionsByLeagueId = (callback) => {
let count = 0;
if (divisions.length === 0) {
return callback('error', null);
}
else {
divisions.forEach((division, dindex) => {
count++;
let inner_count = 0;
if (division.tournament) {
division.players.forEach((player, index) => {
calcTournamentStats(player, division._id, (err, result) => {
inner_count++;
divisions[dindex].players[index] = result;
if (count === divisions.length && inner_count === division.players.length) {
callback(null, 'response which should be caled once');
}
});
});
}
else {
division.teams.forEach((team, index) => {
calcStats(team, division._id, (err, result) => {
inner_count++;
console.log(count +' - '+ divisions.length +' || '+ inner_count +' - '+ division.teams.length);
divisions[dindex].teams[index] = result;
if (count === divisions.length && inner_count === division.teams.length) {
callback(null, 'response which should be caled once');
}
});
});
}
});
}
};
getDivisionsByLeagueId((err, res) => {
console.log(res);
});