Category: How do I do X?
Updated

This solution is summarized from an archived support forum post. This information may have changed. If you notice an error, please let us know in Discord.

API called within forEach loop using unexpected appsmith.store value

Issue

I am using Bitbucket API and JS Object, but I am having trouble retrieving data from a subquery using a stored value from the parent query. The second query returns the same data for every object in the forEach loop, and when including the appsmith.store.repoName output, it does not use the correct value but the last repoName returned from the first query. I tried using Promise.all() to run the loop in parallel, but it overrides the appsmith.store variables, and I am not able to access them in the API calls URL. I need help resolving this issue.

Resolution

The problem was that when using Promise.all() to run API calls in parallel, the appsmith.store variables were being overwritten with the last value in the loop, causing data race issues. One solution is to pass the required variables as parameters to the function being executed by each promise. For example, if iterating over a list of repositories, pass the repository name as a parameter to the function and reference the parameter within that function instead of using appsmith.store variables.

Here is an example code snippet:

const repoList = ["repo1", "repo2", "repo3"];

const promises = [];
for (let i = 0; i < repoList.length; i++) {
const repo = repoList[i];
promises.push((async (repoName) => {
// use the repoName parameter in place of appsmith.store variables
const repoEnvironments = await getRepoEnvironments.run(repoName);
const uuid = repoEnvironments.values.find(object => object.slug.toLowerCase() == environmentList.selectedOptionValue)?.uuid || 'default';

// more code here using repoName and uuid

return tempTable;
})(repo));
}

const results = await Promise.all(promises);
// handle results

By passing in the required variables as parameters, each promise function can execute independently without interfering with each other's reference to the variables.