I want to execute a recursive function that retrieve data from DB. In php the code below run like a charm with 15ms to execute
function GetSubCategories($catno,&$subcats, $useactive=true){
global $dbconn;
$qid = new SSQL($dbconn, "SELECT categoryno FROM article_category WHERE parent = '$catno'".($useactive?" AND active = 'Y'":"")." ORDER BY sortorder");
if ($qid->query()){
while($catrow=$qid->fetch_array()){
$subcats[]=$catrow["categoryno"];
GetSubCategories($catrow["categoryno"],$subcats, $useactive);
}
}
}
I'm a newbie in nodejs environment and Async cause trouble in this case. If i write the same coe in js the program exit after first iteration. I can sync the process with await but execution time explode...
I try many thing with promise like
var getSubcategoriestest = function(categoryno,subcats, useactive=true){
return new Promise(async function (resolve) {
const query = `SELECT categoryno FROM article_category WHERE ?? = ? ${useactive?" AND active = 'Y'":""} ORDER BY sortorder`
let rows = await mysqlConn.query(query,['parent',categoryno])
resolve(rows)
}).then((rows)=>{
for (row of rows){
console.log(row.categoryno)
return new Promise(async function (resolve) {
await getSubcategoriestest(row.categoryno,subcats, useactive)
resolve()
}).then(()=>{console.log('end')})
}
})
}
but nothing work fine
Any guru can help me ?
Thanks
Jeremy
I test this code
var getSubcategoriestest = async function(categoryno,subcats, useactive=true,arrPromise=[]){
let promise = new Promise(function (resolve,reject) {
const query = `SELECT categoryno FROM article_category WHERE ?? = ? ${useactive?" AND active = 'Y'":""} ORDER BY sortorder`
mysqlConn.query(query,['parent',categoryno]).then((rows)=>resolve(rows)).catch(err=>console.log(err))
}).then((rows)=>{
for (row of rows){
getSubcategoriestest(row.categoryno,subcats, useactive,arrPromise).then((rows)=>{subcats.push(row.categoryno)})
}
return row.categoryno
})
arrPromise.push(promise)
Promise.all(arrPromise).then(function() {
console.log("promise all,")
return
}).catch(err=>console.log(err))
}
but function end always after first iteration. Promise.all it's call many times (cause bind at each iteration i suppose)... headache,headache,headache