Last active
March 27, 2025 11:49
-
-
Save Kcko/471d28cf19bb5c15920d4805a8739bc0 to your computer and use it in GitHub Desktop.
This file contains 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
// https://medium.com/@hxu0407/master-these-8-promise-concurrency-control-techniques-to-significantly-improve-performance-5a1c199b6b3c | |
// 1. Promise.all: Execute in Parallel and Return Results Together | |
const promise1 = Promise.resolve(1); | |
const promise2 = Promise.resolve(2); | |
const promise3 = Promise.resolve(3); | |
Promise.all([promise1, promise2, promise3]) | |
.then(results => { | |
console.log(results); // Output: [1, 2, 3] | |
}); | |
// 2. Promise.allSettled: Execute in Parallel and Return All States | |
const promise1 = Promise.resolve(1); | |
const promise2 = Promise.reject("Error"); | |
const promise3 = Promise.resolve(3); | |
Promise.allSettled([promise1, promise2, promise3]) | |
.then(results => { | |
console.log(results); | |
/* Output: | |
[ | |
{ status: 'fulfilled', value: 1 }, | |
{ status: 'rejected', reason: 'Error' }, | |
{ status: 'fulfilled', value: 3 } | |
] | |
*/ | |
}) | |
// 3. Promise.race: Execute in Parallel and Return the Fastest | |
const promise1 = new Promise(resolve => setTimeout(() => resolve("Fast"), 100)); | |
const promise2 = new Promise(resolve => setTimeout(() => resolve("Slow"), 500)); | |
Promise.race([promise1, promise2]) | |
.then(result => console.log(result)); // Output: "Fast" (whichever resolves first) | |
// 4. Promise.any (ES2021): Execute in Parallel and Return the First Fulfilled | |
const promise1 = Promise.reject("Error 1"); | |
const promise2 = new Promise(resolve => setTimeout(() => resolve("Success"), 200)); | |
const promise3 = Promise.reject("Error 2"); | |
Promise.any([promise1, promise2, promise3]) | |
.then(result => console.log(result)) // Output: "Success" | |
.catch(error => console.log(error.errors)); // If all reject | |
// 5. Custom Concurrency Control Function: Limit Max Concurrent Requests | |
async function limitConcurrency(tasks, limit) { | |
const results = []; | |
const running = new Set(); | |
for (const task of tasks) { | |
const promise = task().then(result => { | |
running.delete(promise); | |
return result; | |
}); | |
running.add(promise); | |
results.push(promise); | |
if (running.size >= limit) { | |
await Promise.race(running); | |
} | |
} | |
return Promise.all(results); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment