仅在完成异步处理循环后才渲染视图

时间:2015-11-05 19:35:11

标签: node.js express

我需要帮助我看似无法解决的基本问题。

下面的代码循环输入文件,将行插入数据库并呈现结果视图。

我的问题是视图在所有数据库回调运行之前呈现,因此似乎总是处理0行。

如何在调用所有回调后才能渲染?

router.post('/upload', function(req, res) {
  var good_rows = 0;
  var bad_rows = 0;

  ... // get file data

  _.each(data, function(fileRow) {
      var dbRow = {
          data1: fileRow.data1,
          data2: fileRow.data2
      };

      // insert row to db
      model.create(dbRow, function(insertedCount) {
          // this callback is called only after the view was rendered :(
          if (insertedCount == 1) good_rows++;
          else bad_rows++;
      });
  });

  res.render('upload_result', {
      result: {
          good_rows: good_rows,
          bad_rows: bad_rows,
          log_location: '#'
       }
  });
});

1 个答案:

答案 0 :(得分:1)

您需要在每次回调后检查所有操作是否已完成

  _.each(data, function(fileRow) {
      var dbRow = {
          data1: fileRow.data1,
          data2: fileRow.data2
      };

      // insert row to db
      model.create(dbRow, function(insertedCount) {

          if (insertedCount == 1) good_rows++;
          else bad_rows++;
      //on each callback check if completed
      if(good_rows+bas_rows >= data.length)
         res.render('upload_result', {
            result: {
               good_rows: good_rows,
               bad_rows: bad_rows,
               log_location: '#'
            }
         });
      });
  });