我想执行一个从DB检索数据的递归函数。在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);
}
}
}
我是Node.js环境中的新手,在这种情况下,异步会引起麻烦。 如果我在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多次调用(我想是因为每次迭代都绑定)...头痛,头痛,头痛
答案 0 :(得分:0)
我们在这里
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返回一个诺言。您可以添加一个after after promise.all。