确保每个循环在下一个命令js之前完成

时间:2018-01-26 15:25:22

标签: node.js express foreach

道歉,如果我只是厚厚的。我已经尝试了搜索功能,但对于所有这些都相对较新,我很难找到解决方案。我想我可能没有找到合适的关键字。

我的Node.js应用程序中有一个路由,其中​​有两个forEach循环。我希望forEach循环1完成,然后启动forEach循环2.当完成后,我想调用我的res.redirect。目前该路线直接进入res.redirect,并且似乎没有完成forEach循环。

代码:

// Auto-populate entries
router.post("/populate", middlewareObj.isLoggedIn, function(req, res) {
  var baseData = []
  //lookup Plan using ID
  Plan.findById(req.params.id, function(err, foundPlan) {
    if (err) {
      console.log(err);
      res.redirect("/plans");
    } else {
      BaseData.find({
        "contributingRegion": foundPlan.contributingRegion
      }, function(err, foundRecords) {

        foundRecords.forEach(function(record) {
          baseData.push(record)
          baseData.save
        });

        //Create entries & push into plan
        baseData.forEach(function(data) {
          if (includes(req.body.orgs, data.org)) {
            Entry.create(data, function(err, entry) {
              if (err) {
                console.log(err);
              } else {
                entry.author.id = req.user._id;
                entry.author.username = req.user.username;
                entry.save();
                foundPlan.planEntries.push(entry);
                foundPlan.save();
              }
            })
          }
        })

        res.redirect('/plans/' + foundPlan._id);
      });
    }
  });
});

1 个答案:

答案 0 :(得分:0)

有很多方法可以实现这一点,例如你可以使用promisesasync module,你也可以使用recurrent functions,我将提供async模块的解决方案,因为它让您了解异步函数的工作原理以及如何控制它们:

async.each( baseData, function (data, next) {

    if (includes(req.body.orgs, data.org)) {

        Entry.create(data, function(err, entry) {

            if (err) {
                // stop iterating and pass error to the last callback
                next(err);
            } else {
                entry.author.id = req.user._id;
                entry.author.username = req.user.username;
                entry.save();
                foundPlan.planEntries.push(entry);
                foundPlan.save();
                // next iteration
                next();
            }

        });

    } else {
        // next iteration
        next();
    }

}, function (err) {

    // This function runs when all iterations are done

    if (err) throw err;

    res.redirect('/plans/' + foundPlan._id);

} );