Node.js 在nodejs中同步循环?
这是我的密码Node.js 在nodejs中同步循环?,node.js,Node.js,这是我的密码 function getallCollections(cb) { var query = "select id,name from categories where parent_id is NULL LIMIT 4"; var collection_menu = []; con.query(query, (err, result) => { if (result) { // get result flag
function getallCollections(cb) {
var query = "select id,name from categories where parent_id is NULL LIMIT 4";
var collection_menu = [];
con.query(query, (err, result) => {
if (result) { // get result
flag = 0;
for (i = 0; i < result.length; i++) {
var inner_query = "select * from categories where parent_id = " + result[i].id + " LIMIT 6";
con.query(inner_query, function(err, inner_result) {
if (inner_result) { //get new result
console.log(result[i].name)
flag++;
inner_result.parent_name = result[i].name // producing value of result[0].name in each loop
collection_menu.push(inner_result)
if (flag === 4) {
cb(collection_menu)
}
} else {
console.log(err)
}
})
}
}
})
}
函数getallCollections(cb){
var query=“从父项id为空限制4的类别中选择id、名称”;
变量集合菜单=[];
con.query(查询,(错误,结果)=>{
if(result){//get result
flag=0;
对于(i=0;iinternal\u result.parent\u name
的值始终相同。我知道这是因为async for循环,但我无法获得正确的值。
对于
内部结果
用以下代码替换for循环,if块中i的值不递增:
// try know about async library
async.map(result, function(each, next) {
//better way -- select the data you required to process so that you don't need the flag
var inner_query = "select * from categories where parent_id = " + each.id + " LIMIT 6";
con.query(inner_query, function(err, inner_result) {
if (inner_result) { //get new result
inner_result = JSON.parse(JSON.stringify(inner_result));
console.log(each.name);
flag++;
inner_result.parent_name = each.name; // producing value of result[0].name in each loop
collection_menu.push(inner_result);
if (flag === 4) {
//try to avoid flag | but here is how you can break
next(true);
} else {
next();
}
} else {
console.log(err)
next();
}
});
}, function(error, result) {
if (error == true) {
// your noraml flow after flag == 4
cb(collection_menu);
} else {
// your code
}
// hope this work | minor changes may require
})
谢谢它起作用了。。。我还将看到异步库