这是我的代码:
var shopId=[1,2,3,4];
async.each(shopId,function (item,callback) {
model.client.query("SELECT categoryId shopId=? ", [shopId], function (err, rows) {
if (rows.length > 0) {
var asyncData = rows;
//categoryId will be in the format [1,2,3,4]
async.each(asyncData,function (item, callback) {
var categoryId = item.categoryId;
async.series([
function (callback) {
model.client.query("select categoryName from category where categoryId = ?", [categoryId], function (err, data) {
callback(null, data);
});
}],
function (err, results) {
item.category = results[0];
callback();
});
},function (err) {
callback(asyncData); //getting data here
});
}
});
},function (err,result) {
res.json(result); //not getting data here
});
我是aysnc方法的新手。我无法将结果传递给最终功能。
答案 0 :(得分:0)
假设有一个shop
表,您可以加入表来保存查询。
const sql = 'select categoryName from category as c inner join shop as s on c.categoryId = s.categoryId where s.shopId = ?'
然后
const shopId = [1, 2, 3, 4];
const finalResult = [];
async.each(shopId, function(item, callback) {
model.client.query(sql, [shopId], function (err, rows) {
// do not forget error handling !
if (rows.length > 0) {
finalResult.push(rows);
return callback();
}
return callback(); // do not forget to return callback in every case
});
}, function(err) { // in async each callback, you only get errors
if (err)
return res.json(err); // or whatever error handling
res.json(finalResult);
});
另外,考虑到您的代码,我建议您对回调进行不同的命名以避免错误或忘记。即。
async.each([], function(item, cbkGlobal) {
async.each([], function(item, cbkEach) {});
});
当您希望多个函数按顺序执行时,async.series
非常有用。但在这里你只执行一个函数......