Trying to get data from the inner loop, but getting with delay.
In the code, I am getting the user list from the sql table with their ancestors. I need these ancestors to check their root values(hierarchy/tree structure). If the ancestor role is salesmanager, then add salesmanager name for each user.
Case which is not working:
If a user itself is parent, value pushes into array. (WORKS)
If a user has parent (like user_id 3 is added by user_id 2, and 2 is added by 1), 1 is ancestor of 3. Goes to inner loop.
Value pushes to the same array, displays if prints inside this array but didn't display if prints outside the loop
Here is the code:
var sql_query='SELECT *,GetAncestry(id) as anstry FROM users' //get ancestors using sql function
con.query(sql_query, function(err,rows) {
if(err) throw err;
if(rows) {
console.log('length rows'+rows.length) // prints 5
var rows_salesinfo=[]
var ancestors=[]
rows.forEach(function(rows) {
if(rows.anstry !='') {
var array = JSON.parse("[" + rows.anstry + "]");
} else {
var array = []
}
if(array.length > 0) {
// inner loop starts
con.query('SELECT id,role,firstname,lastname FROM users WHERE users.id IN ('+array+')', function(demoErr,demoRows) {
if(demoErr) throw demoErr;
if(demoRows.length > 0) {
var keepGoing = true;
demoRows.forEach(function(index,value,callback) {
if(keepGoing) {
if(index.role == 'sales_manager') {
console.log(rows.id)
rows.salesmanager = index.firstname+" "+index.lastname
rows_salesinfo.push(rows)
keepGoing = false;
}
}
console.log(rows_salesinfo) // this inner loop values print here
})
} else {
rows_salesinfo.push(rows)
}
})
} else {
console.log(rows.id) // works
rows.salesmanager=''
rows_salesinfo.push(rows) // works
}
})
console.log('6new')
console.log(rows_salesinfo) // works before response of inner loop
console.log('length rows_salesinfo'+rows_salesinfo.length) // length 3
}
})