AI summary by TwinMind
The Dangers Of Promise.all()
Theo - t3․gg
6m 14s
Promise.all Problems and Limitations
- Demo setup: React app with button triggering promise.all
- Array [1,2,3,4,5] mapped to async work function
- Work function: waits number * 1000ms, returns number squared
- Promise.all failure behavior:
- When one promise fails (e.g., number 4), entire operation fails
- Remaining promises continue running in background but results lost
- All completed work vanished "Into The Ether"
- Uncaught promise rejection if no try-catch
- Core issue: No access to successful results when any promise fails
Promise.allSettled as Superior Alternative
- Identical setup but using Promise.allSettled instead of Promise.all
- Key difference: Returns results for both fulfilled and rejected promises
- Failure handling:
- 4 calls fulfilled, 1 rejected
- All results accessible regardless of individual failures
- Error caught and handled gracefully
TypeScript/Type Safety Challenges
- Promise.allSettled returns PromiseSettledResult type
- Type filtering complexity:
const errors = results.filter(result => result.status === 'rejected')const successes = results.filter(result => result.status === 'fulfilled')
- TypeScript doesn't recognize filtered results maintain specific status
- Still shows union type after filtering
- Requires type guards for proper typing
- Promise.all simpler typing: direct number array result
- Trade-off: More complex typing for better error handling
Recommendation and Best Practices
- Promise.allSettled forces consideration of error/success cases
- Makes developers think about failure scenarios upfront
- Improves code readability for error case handling
- Promise.all creates "nasty edge cases" that confuse consumers
- General recommendation: Use Promise.allSettled over Promise.all
- Challenge to audience: Find legitimate Promise.all use cases
