Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在for循环中执行异步函数_Javascript_Node.js - Fatal编程技术网

Javascript 如何在for循环中执行异步函数

Javascript 如何在for循环中执行异步函数,javascript,node.js,Javascript,Node.js,首先,我正在搜索用户所属的所有组的GroupMember模型。当他们被发现时,我得到了结果 我想循环查看结果,并从组模型中获得每个组。但是,我如何在for/forEach的中执行异步函数,并且仅在异步函数完成时才转到下一个迭代 因为现在groups数组将一次又一次地进行第一次迭代 GroupMember.findAll({ Where : { userID : userID } }) .then(function(result) { var group

首先,我正在搜索用户所属的所有组的GroupMember模型。当他们被发现时,我得到了结果

我想循环查看结果,并从模型中获得每个组。但是,我如何在for/forEach的中执行异步函数,并且仅在异步函数完成时才转到下一个迭代

因为现在groups数组将一次又一次地进行第一次迭代

GroupMember.findAll({
    Where : {
      userID : userID
    }
  })
  .then(function(result) {
    var groups = []
    var itemsProcessed = 0;

    result.forEach(function(listItem, index, array) {
      var groupID = listItem.dataValues.groupID;

      Group.find({
        Where : {
          groupID: groupID
        }
      })
      .then(function(group) {

        groups.push(group.dataValues);
        itemsProcessed++;
        if(itemsProcessed === array.length) {

          done(null, groups);
        }
      });
    })

  })
  .catch(function(error) {
    done(error);
  });


编辑

集团模式

module.exports.getMyGroups = function(userID) {

  return GroupMember.findAll({ attributes: ['groupID'], where: { userID: userID } })
      .then(function(result) {
        return Promise.all(result.map(function(listItem) {
            var groupID = listItem.dataValues.groupID;

            return Group.find({
              attributes: ['groupName', 'groupDescriptionShort', 'createdAt'],
              where: { id: groupID }
            })
                .then(function(group) {
                  return group.dataValues;
                });
        }));
      });

}
module.exports.myGroups = function(req, res) {
  var userID = req.body.userID;

  group.findByUserId(userID).then(
    function(groups) {
      respHandler.json(res, 200, { "groups": groups });
    },
    function(error) {
      respHandler.json(res, 400, { "error": error });
    });
}
呼叫模型的组控制器

module.exports.getMyGroups = function(userID) {

  return GroupMember.findAll({ attributes: ['groupID'], where: { userID: userID } })
      .then(function(result) {
        return Promise.all(result.map(function(listItem) {
            var groupID = listItem.dataValues.groupID;

            return Group.find({
              attributes: ['groupName', 'groupDescriptionShort', 'createdAt'],
              where: { id: groupID }
            })
                .then(function(group) {
                  return group.dataValues;
                });
        }));
      });

}
module.exports.myGroups = function(req, res) {
  var userID = req.body.userID;

  group.findByUserId(userID).then(
    function(groups) {
      respHandler.json(res, 200, { "groups": groups });
    },
    function(error) {
      respHandler.json(res, 400, { "error": error });
    });
}
呼叫组控制器的路由器

router.post('/groups', groupCtrl.myGroups);

您可以使用
Promise.all
更好地处理多个类似Promise的执行

  GroupMember.findAll({
    Where : {
      userID : userID
    }
  })
  .then(function(result) {
     return Promise.all(result.map(function (listItem) {
        var groupId = listItem.dataValues.groupID;

        return Group.find({ Where: { groupId: groupId })
                    .then(function (group) {
                         return group.dataValues;
                    });
     }));
   })
   .then(function (groups) {
      done(null, groups);
   })
   .catch(function(error) {
      done(error);
   });
但是如果你真的需要等待每一次迭代,然后再进行下一次迭代,我会使用其他类似的函数

GroupMember.findAll({
    Where: { userId: userId }
}).then(function (result) {
    var array = [];

    function next () {
        var groupId = result[array.length].dataValues.groupId;

        Group.find({ Where: { groupId: groupId })
             .then(function (group) {
                 array.push(group.dataValues);

                 if (array.length >= result.length) {
                     done(null, array);
                 } else {
                     next();
                 }
             })
             .catch(function (error) {
                 done(error);
             });
    }(); // Directly executed
})
.catch(function(error) {
   done(error);
});

不要使用带有承诺的
done
回调。把承诺还给我!删除所有涉及
done
,在
findUserByID
正文前加上
return
,然后将其称为
group.findByUserId(userID,function(groups){respHandler.json(res,200,{“groups”:groups};},function(error){respHandler.json(res,400,{“error”:error});})
你说得对,我忘了用
替换逗号)。然后(
。关于控制器,它总是需要处理错误(拒绝承诺)在链的末尾。不,你根本不应该
返回错误
。放弃整个
catch
调用,这样你就可以直接返回承诺,并实现承诺或拒绝承诺。@Bergi我想我理解你,我在帖子中更新了我的模型。