无法获取db Query执行回调之外的值

时间:2017-11-15 12:38:49

标签: node.js angular

我是nodejs的新手,帮助我理解

  

无法获取categories数组中的值,就像我在forloop外打印值一样

     

如果我在第二个查询中打印,则打印更改

var sql = 'select * from categories where adp_customers_id = ?  and parent_id = 0 and display_on_screen = 1  and category_type= \'COLLECTION\' ';
mysqlConnection.query(sql,[ adpCustomer ],  function (err,  result) {
if (err) throw err;
var categories = [];  // i think values should be reflected here nut no luck, what im missing  
if(result.length > 0){
for(var a =0; a<result.length ; a++){
var subcategories = [];
var currentCategory = 0;
currentCategory = result[a].id;
var name = result[a].name;
var description = result[a].description;
var sql = 'select * from categories where adp_customers_id = ?  and parent_id = ? and display_on_screen = 1  and category_type= \'COLLECTION\'';
    mysqlConnection.query(sql, [adpCustomer, currentCategory],  function (err, subCategoryResult) {
if (err) throw err;
if (subCategoryResult.length > 0) {
for (var a = 0; a < subCategoryResult.length; a++) {
subcategories.push({
"id": subCategoryResult[a].id,
"name": subCategoryResult[a].name,
"description": subCategoryResult[a].description,
});
}
}
categories.push({
"id": currentCategory,
"name": name,
"description": description,
"children": subcategories
});
console.log("categores = "+  JSON.stringify(categories));   // working here
});
}
console.log("categores = "+  JSON.stringify(categories));   // not working here WHY
return res.json(categories);
}
});

1 个答案:

答案 0 :(得分:0)

因为您在查询的回调函数中填充数组。 “working”行在回调范围内,控制台日志在您处理数据后立即发生。另一个在外面,在回调结束之前执行。

你应该看看Promises(或回调),这将永远不会这样。