确保forEach循环在下一个命令js之前完成 [英] ensure forEach loop finishes before next command js

查看:325
本文介绍了确保forEach循环在下一个命令js之前完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果我很胖.我已经尝试过搜索功能,但是相对于所有这些而言,我还是比较陌生,因此我正在努力寻找解决方案.我想我可能没有在搜索正确的关键字.

Apologies if I'm just being thick. I've tried the search function, but being relatively new to all of this, I'm struggling to work out the solution. I think I'm probably not searching for the right keyword.

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

I have a route in my Node.js application that has two forEach loops in it. I want forEach loop 1 to finish, then start forEach loop 2. When that finishes, I then want to call my res.redirect. Currently the route is going straight to res.redirect, and doesn't appear to be completing the forEach loops.

代码:

// 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);
      });
    }
  });
});

推荐答案

有很多方法可以实现此目的,例如,您可以使用异步模块,您可以还使用递归函数,我将提供异步模块解决方案,因为它允许您了解异步功能如何工作以及如何控制它们:

There are many ways to achieve this, for example you could use promises or async module, you could also use recurrent functions, I will provide a solution with the async module because it let you understand how asynchronous functions work and how to control them:

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);

} );

这篇关于确保forEach循环在下一个命令js之前完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆