node.js - 在nodejs中同步For循环?
问题描述
这是我的代码
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)
}
})
}
}
})
}
这里的值inner_result.parent_name
总是相同的。我知道这是因为异步 for 循环,但我无法获得正确的值。i 的值在 if 块中没有递增inner_result
。
解决方案
用下面的代码替换你的 for 循环:
// 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
})
推荐阅读
- google-sheets - Google 表格中的公式
- c# - 在推动页面停止移动时加载带有 gif 的弹出页面 - Xamarin Forms
- apache-spark - Pyspark 从数组列表转换为字符串列表
- angular - 如何更改角度 6 折线图的横坐标
- python - Python 3 为什么返回无
- visual-studio-code - 如何在 VS Code 中设置 GLFW?GLFW 错误
- vue.js - 同一组件之间的过渡?
- google-bigquery - BigQuery 数据仓库/实时数据/配额
- c# - 如何通过 Wix Boostrapper 在修改模式下添加包?
- laravel - 如何在已经托管在我的 cpanel 中的现有 laravel 网站中安装 tawk 聊天