简体   繁体   中英

How to chaining await functions together

I have 3 async / await calls that depend on each other, trying to figure out how to chain them. Hand-coded this is what it looks like

// 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'])

Trying to figure out how to map through this to get a list of all organizations, each with its members and each member with its roles.

So far this is where I have gotten to:

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

Sounds like you're looking for

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM