【问题标题】:async.each not giving the result?async.each 没有给出结果?
【发布时间】:2017-08-22 22:45:59
【问题描述】:

这是我的代码:

 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 方法的新手。我无法将结果传递给最终函数。

【问题讨论】:

  • 您可以在第一个 async 块上方声明一个对象,然后将任何结果附加到它并在最终回调中使用它。如果您使用的是 express,您可以使用 req 对象。但是你必须在多个中间件中打破这个代码块,它非常嵌套,因此更容易出错且难以理解。
  • 使用async.map 而不是each
  • 你在使用 mysql 吗?我认为你的代码可以变得更干净
  • @Jérôme ya,我正在使用我的 sql

标签: node.js express async.js


【解决方案1】:

假设有一个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 很有用。但在这里你只执行一个功能......

【讨论】:

    猜你喜欢
    • 2018-11-30
    • 2014-03-12
    • 1970-01-01
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 2023-03-16
    • 2019-05-17
    相关资源
    最近更新 更多