在node.js中的for循环内同步异步调用

时间:2018-01-25 07:01:23

标签: javascript node.js asynchronous

我有两个mongo模型。 User模型包含一个字段'groups',它是一个数组,包含用户所属的所有组ID。群组模型包含有关群组的所有信息,例如群组名称,所有者等。我想获取所有用户群组的数组,并在响应中包含“群组名称”和“群组所有者”等详细信息。

请注意:我有两个异步调用。下面的所有代码都在另一个帖子方法中。

//First Async Call
    User.getGroupsByUsername(req.user.username, (err, groups) => {
                let userGroups = [];
                for (let group of groups) {
                    temp.group_id = group.group_id;
                    temp.role = group.role;
//Second Async call within for loop
                    User.getGroupsDetails(group_id, (err, groupInfo) => {
                        temp.group_name = groupInfo.name;
                        temp.group_owner = groupInfo.owner;
                    });
//temp.group_name and temp.group_owner are still unassigned because of async call
                    userGroups.push(temp);
                    temp = null;
                }
                res.json({
                    success: true,
                    groups: userGroups
                });
            });

当上述代码到达userGroups.push(temp); userGroupstemp未定义时(请参阅代码注释)。

我尝试操纵查询,但是mongo聚合似乎不会以我需要的格式产生结果,这将是另一个主题。我想知道如何使用node.js生成这样的响应。提前谢谢。

0 个答案:

没有答案
相关问题