首页 > 解决方案 > 递归nodejs mysql查询

问题描述

我想执行一个从数据库中检索数据的递归函数。在 php 中,下面的代码运行起来就像一个魅力,需要 15 毫秒来执行

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);
      }
    }

}

我是 nodejs 环境中的新手,在这种情况下 Async 会引起麻烦。如果我在 js 中编写相同的 coe,程序会在第一次迭代后退出。我可以将进程与 await 同步,但执行时间会爆炸......

我尝试了很多事情,比如

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')})
    } 
})

}

但没有什么可以正常工作

任何大师可以帮助我吗?

谢谢

杰里米


我测试这段代码

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))

}

但函数总是在第一次迭代后结束。Promise.all 它被调用了很多次(我想每次迭代都会绑定)......头痛,头痛,头痛

标签: node.jsasynchronousrecursion

解决方案


开始了

var getSubcategoriestest = function (categoryno,subcats) {

   const query = `SELECT c FROM ac WHERE ?? = ? ORDER BY sortorder`

   return mysqlConn.query(query,['parent',categoryno]).then(rows => {   
        return Promise.all(rows.map(row => {
            subcats.push(row.categoryno);
            return getSubcategoriestest(row.categoryno, subcats,useactive);
        }));
   })}

rows.map 制作一个承诺数组,因为 getSubcategoriestest 返回一个承诺。你可以在 promise.all 之后添加 then。


推荐阅读