开发者问题收集

如何将 await 函数链接在一起

2021-05-12
72

我有 3 个相互依赖的 async / await 调用,试图弄清楚如何链接它们。 手工编码后如下所示

// list of organizations
const { orgs } = await organizations();

// list of members belonging to single organization
const { members } = await organization_members(orgs[0]['id']);

// roles belonging to a user in an organization
const { roles } = await organization_member_roles(orgs[0]['id'], members[0]['user_id'])

试图弄清楚如何映射它以获取所有组织的列表,每个组织都有其成员,每个成员都有其角色。

到目前为止,这是我得到的:

  const get_members = async (org) => {
    const { members } = await organization_members(org.id)
    return members
  }

(async () => {
  const members = await Promise.all(orgs.map(org => get_members(org)))
  console.log(members)
})();
1个回答

听起来您正在寻找

async function orgsWithMembersWithRoles() {
    const { orgs } = await organizations();
    return Promise.all(orgs.map(async (org) => {
        const { members } = await organization_members(org.id);
    
        return {
            org,
            members: await Promise.all(members.map(async (member) => {
                const { roles } = await organization_member_roles(org.id, member.user_id)
                return {
                    member,
                    roles,
                };
            })),
        };
    }));
}
Bergi
2021-05-13