Best way to call api while looping through array

Hi guys

I’ve been developing a few apps here and there to help my team with mundane tasks.

One problem I’ve stumbled across a few times, is that sometimes, I need to loop through a list of items and call the api to perform some functions.

With Custom UI, I get an error, that there is a Rate Limiter of 20req per 2seconds on the Resolver.
With UI Kit, I don’t seem to get any errors, but nothing seems to happen.

I’m working on an app in UI kit right now, where I want to create an organisation (in JSM). Then I want to loop through each Service Project and add this organisation to the project.

When I call the endpoint just once to add an Organisation to one project - everything is fine. But when I use a map, to iterate through my Project collection and call my function, it just seems that nothing happens at all.

What would be the best way to iterate through an object and perform updates to the api?

I have tried variations of Promise and Promise.All, but took that out as I’m a bit of a noob with it.

const syncOrganization = async (organization) =>
    {
        const usersFromGroup = await getUsersFromGroup(organization);
        storage.set(organization, `Organisation created and ${usersFromGroup.length} user(s) added`);
        await (addUsersToOrganisation(usersFromGroup, organizations.values.find(org => org.name === organization).id))
        projects.values.map(async(project)=>
        {
            let organizationid = organizations.values.find(o => o.name === organization).id;  
            await addOrganisationToProject(project.id,organizationid);
        })
    }

const addOrganisationToProject = async (projectId, organizationId) => {
        const params = JSON.stringify({ "organizationId": organizationId });
        console.log(params);
        console.log(`${baseUrl}/rest/servicedeskapi/servicedesk/${projectId}/organization`);
        const result = await api.fetch(
            `${baseUrl}/rest/servicedeskapi/servicedesk/${projectId}/organization`,
            {
                method: 'POST',
                body: params,
                headers:
                {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'Authorization': token
                }
            }
        );
        const status = await result.status;
        console.log(`Status of adding organisation to project: ${status}`);
    }

1 Like

Can you start by putting an await Promise.all on your map?

Currently your code does not wait for any of the promises that the map creates to finish.

2 Likes

This worked, thanks @rmassaioli

I tried the Promise.all before, but I think what I was missing, was the “await” before the Promise.all.

Appreciate it man.

2 Likes

Awesome! I’m happy that helped!

1 Like