Performance: Promise.race and Promise.allSettled
This concept affects how asynchronous operations impact page responsiveness and resource usage during concurrent tasks.
Jump into concepts and practice - no test required
await Promise.race([task1(), task2(), task3()]); // resolves or rejects as soon as one task settles
await Promise.allSettled([task1(), task2(), task3()]); // waits for all tasks to finish
| Pattern | Async Wait Time | UI Responsiveness | Resource Usage | Verdict |
|---|---|---|---|---|
| Promise.allSettled for first result | Long (waits all) | Low (delayed) | High (all tasks run fully) | [X] Bad |
| Promise.race for first result | Short (first settles) | High (fast response) | Moderate (tasks still run) | [OK] Good |
| Promise.all for all success | Medium (waits all success) | Medium (may reject early) | High (may retry) | [!] OK |
| Promise.allSettled for all results | Long (waits all) | High (stable UI) | Moderate (no retries) | [OK] Good |
Promise.race do when given multiple promises?Promise.allSettled with an array of promises named tasks?const p1 = new Promise(res => setTimeout(() => res('A'), 100));
const p2 = new Promise((_, rej) => setTimeout(() => rej('Error'), 50));
Promise.race([p1, p2])
.then(console.log)
.catch(console.error);const promises = [Promise.resolve(1), Promise.reject('fail')];
Promise.allSettled(promises).catch(console.error);task1, task2, and task3. You want to get the first task that finishes successfully, but if all fail, you want to know all errors. Which approach correctly achieves this?