Skip to content

Instantly share code, notes, and snippets.

@banderson5144
Last active February 1, 2025 00:01
Show Gist options
  • Save banderson5144/aab6bbe61981705a8215d95830e53f88 to your computer and use it in GitHub Desktop.
Save banderson5144/aab6bbe61981705a8215d95830e53f88 to your computer and use it in GitHub Desktop.
Stop Boxcar effect in LWC (in conjunction with @zerkz)
//Original code from Stackoverflow
// https://stackoverflow.com/questions/70470728/how-can-i-execute-some-async-tasks-in-parallel-with-limit-in-generator-function/77021751#77021751
const mapParallel = async (values, fn) => {
const promises = new Set(); //Complete result set after all executions are complete
const tmpPromises = new Set(); //Container array to only allow 5 Pending promises at a time
const MAX_APEX_CALLS = 5;
for (const i in values) {
//if the size of our temp array is greater than or equal the max number of calls
//we need to wait for one of them to finish before adding another one
while (tmpPromises.size >= MAX_APEX_CALLS){
//Wait for the first promise to finish
//Not the first in the array, but in any position
await Promise.race(tmpPromises.values());
//The finally clause of the promise runs
//This removes the finsihed promise from the temp Array to allow the next Apex call
}
let promise = fn(values[i], i).finally(() => {
//delete itself from the container array since it is done
tmpPromises.delete(promise)
});
promises.add(promise);
tmpPromises.add(promise);
}
return Promise.all(promises.values());
};
let apexPromiseResults = mapParallel([Array Of Params To send To Apex...],
async (value, index) => {
return await auraEnabledApexMethod({apexParam:value});
});
//now you can loop over the results from apexPromiseResults
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment