首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >确保在下一个命令js之前完成forEach循环

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

Stack Overflow用户
提问于 2018-01-26 23:25:22
回答 1查看 479关注 0票数 1

如果我太粗鲁了,我很抱歉。我已经尝试过搜索功能,但作为一个相对较新的人,我正在努力寻找解决方案。我想我可能没有搜索到正确的关键字。

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

代码:

代码语言:javascript
复制
// 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);
      });
    }
  });
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-26 23:53:52

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

代码语言:javascript
复制
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);

} );
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48464355

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档