我希望从查询中获取数据,然后对存储在result中的项运行数组循环。然后使用从第一个查询获取的数组中的键从另一个查询中获取数据。
我所尝试的并没有给出我想要的结果,因为在sql查询完成并产生所需结果之前,数组循环用完了。
我尝试过使用async.series函数和async.map函数的解决方案,但结果并没有按照所需的顺序进行。
这是第一个查询的输出。 我的目标是添加从第一个查询返回的选项ID的数组选项ID。
[
{
"id": 318,
"name": "Sandwich Dosa",
"price": 140,
"option": ''
},
{
"id": 319,
"name": "Spi. Prem Uttappa",
"price": 131,
"option": '1,2'
},
{
"id": 320,
"name": "Paneer Spl. Prem Uttappa",
"price": 140,
"option": ''
},
{
"id": 321,
"name": "Spl. Spicy Uttappa",
"price": 131,
"option": ''
}
]
希望构建为
[
{
"id": 318,
"name": "Sandwich Dosa",
"price": 140,
"option": ''
},
{
"id": 319,
"name": "Spi. Prem Uttappa",
"price": 131,
"option": [{
id:'1',
name:'Regular',
price:'89',
},
{
id:'2',
name:'Spicy',
price:'119',
}]
},
{
"id": 320,
"name": "Paneer Spl. Prem Uttappa",
"price": 140,
"option": ''
},
{
"id": 321,
"name": "Spl. Spicy Uttappa",
"price": 131,
"option": ''
}
]
这是我目前正在试图实现的代码
var data = {
"error": 1,
"items": ""
};
connection.query("SELECT * FROM items WHERE status=1 AND menu_grp_id=" + req.params.sid, function(err, rows, fields) {
var items = []; // temporary holder for items
if(err) { throw err } else {
if(rows.length != 0) {
for (var key in rows) {
// Holding Item properties
var item = {
id: '',
name: '',
price: '',
option: ''
};
item.id = rows[key].id;
item.name = rows[key].item_name;
item.price = rows[key].price;
item.option = rows[key].option;
items.push(item); // pushing item object into items array
}
data["error"] = 0;
data['items'] = items;
if((data['items'].length > 0)) {
for(i = 0; i < data['items'].length; i++) {
if(data['items'][i].option == "") {
data['items'][i].option = [];
} else {
var array = data['items'][i].option.split(",")
data['items'][i].option = array;
}
}
}
res.json(data); // sending JSON Data
} else {
data["error"] = 0;
data["items"] = 'No item Found..';
res.json(data); // sending JSON Data
}}
});
答案 0 :(得分:0)
可能我在这里有点晚了,但我认为async.waterfall就是你所需要的。
async.waterfall([
function(cb){
connection.query("SELECT * FROM items WHERE status=1 AND menu_grp_id=" + req.params.sid, function(err, rows, fields) {
//manipulate your data as you wish
data = synchronousManipolutionOfYourData();
cb(null, data);
});
},
function(data, cb){
//data here stores the data you passed as a second parameter in the preciding callback
//execute your second query with the data you got from the first query.
cb(null, dataManipulatedAfterSecondQuery)//and so on
},
//other functions if you need other queries
], function(){
done;
});