Kingsley Ijomah
Kingsley Ijomah

Reputation: 3403

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

Upvotes: 0

Views: 77

Answers (1)

Bergi
Bergi

Reputation: 664538

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

Upvotes: 1

Related Questions