【问题标题】:async.each not processing mongoose find functionasync.each 不处理猫鼬查找功能
【发布时间】:2018-08-04 04:26:22
【问题描述】:

我有以下代码:

    async.each(arrayUser, function (user, callback) { //loop through array
      console.log('1');
      async.each(user.parentOf, function (child, callback1) { //loop through array
        console.log(2);
        models.Students.find({
            '_id': child._id
          },
          function (err, foundStudent) {
            console.log('3');
            callback1();
          },
          function (err) {
            console.log("InnerLoopFinished");
            callback();
          });
      }, function (err) {
        console.log("OuterLoopFinished");
        console.log('Process Finished');
      });
    });

arrayUser 是这样创建的:

    var arrayUser = [];
    users.forEach(function (user) {
      var arrayUser1 = {
        parent: {
          _id: user._id,
          firstName: user.firstName,
          lastName: user.lastName
        },
        userRoleID: user.userRoleID.length,
        parentOf: user.parentOf

      };
      arrayUser.push(arrayUser1);
    });

user.parentOf 的一个示例是:

    user.parentOf = [{
        studentLastName: 'Flores',
        studentFirstName: 'Aedan',
        studentID: 111444,
        _id: 5a596979ea2d7a360c75948c
      },
      {
        studentLastName: 'Moses',
        studentFirstName: 'Chase',
        studentID: 111756,
        _id: 5a596979ea2d7a360c759489
      }
    ]

我的问题是,即使使用async.each 该功能仍然无法正常运行。当它到达models.Students.find 函数并运行下一个回调时,它似乎正在碰壁。

在继续下一个user 之前,我需要完全运行 InnerLoop。 我按照正确答案nodejs Async.each Nested loop Confusion 但没有结果。我尝试将 models.Students.find 函数更改为 findOneAndUpdate 并得到相同的结果。

我想我需要补充一点,我需要找到多个用户,每个用户都有一个内部数组。如果我只有一个用户(没有外循环),它可以正常工作。

我的 console.log 是:1, 2, 1, 2, 1, 2 ... 3, 3, 3...

我需要它是 1、2、3、1、2、3。

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    我们需要使用 async.eachSeries() 而不是 async.each()。这是符合您期望 1、2、3、1、2、3 的工作 sn-p。

    async.eachSeries(arrayUser, function (user, callback) { //loop through array
          console.log('1');
          async.eachSeries(user.parentOf, function (child, callback1) { //loop through array
            console.log(2);
            models.Students.find({
                '_id': child._id
              },
              function (err, foundStudent) {
                console.log('3');
                callback1();
              });
          },function (err) {
            console.log("InnerLoopFinished");
            callback();
          });
        }, function (err) {
            console.log("OuterLoopFinished");
            console.log('Process Finished');
          });
        });
    

    这是因为 eachSeries 函数按顺序在 iteratee 函数中执行(在完成上一次迭代后等待 callback() 被调用)所以它会根据您的期望给出输出

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-17
      • 2019-02-27
      • 2018-02-16
      • 2015-12-11
      • 1970-01-01
      • 1970-01-01
      • 2016-11-18
      相关资源
      最近更新 更多