node.js - 递归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 它被调用了很多次(我想每次迭代都会绑定)......头痛,头痛,头痛
解决方案
开始了
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。
推荐阅读
- ruby-on-rails - 在其他字段上触发验证时复选框未保持选中状态
- json - 仅使用 Angular 7 将 json 数据写入本地 JSON 文件
- google-apps-script - 比较两列的匹配项并拉取每个匹配项的相邻值
- c# - 如何在没有 API 的情况下获取 Instagram 页面的关注者数量
- javascript - 使用 [FromForm] 属性时,集合始终为空
- regex - 匹配浮点数的任务
- javascript - 如何在 setInterval 方法中获取更新的会话变量
- pandoc - 在 pandoc 中保留空间
- android - 如何在文本输入中禁用文本下的行 android react native
- python - 使用请求在 Python 中发布文件数组时出现 TypeError