I use recursion in the javascript async function to count the number of employees working under each manager. Try to understand what is wrong with my function and why it returns only the half amount of employees
async function countEmployees(E, count) {
if (E.employees === 'undefined' || E.employees == null) {
return 0
}
else {
count += E.employees.length
E.employees.forEach(async emp => {
console.log('id:', emp.id, 'count:', count)
await countEmployees(emp, count)
})
}
}
UPDATE: I think I solved it! Was constantly overriding the count Now the modified version works
var count
async function countEmployees(E) {
if (E.employees === 'undefined' || E.employees == null) {
return 0
}
else {
count += E.employees.length
for (const ind in E.employees) {
if (Object.hasOwnProperty.call(E.employees, ind)) {
const emp = E.employees[ind];
await countEmployees(emp)
}
}
}
}
setTimeout(() => {
console.log(count) }, 5000);