Last active
February 1, 2025 00:01
-
-
Save banderson5144/aab6bbe61981705a8215d95830e53f88 to your computer and use it in GitHub Desktop.
Stop Boxcar effect in LWC (in conjunction with @zerkz)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //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