JavaScript Promises
š¤ Promise Basics
Promises represent the eventual completion (or failure) of an asynchronous operation and its resulting value. They're essential for managing async code in JavaScript.
Promise States:
- Pending - Initial state
- Fulfilled - Operation completed successfully
- Rejected - Operation failed
Promise Methods:
.then()- Handle fulfillment.catch()- Handle rejection.finally()- Execute always
š§ Promise Static Methods
The Promise API provides several static methods for working with multiple promises. These are essential for complex async operations.
Static Methods:
Promise.all()- All must succeedPromise.allSettled()- Wait for allPromise.race()- First to settlePromise.any()- First to succeed
Use Cases:
Promise.all()- Parallel independent requestsPromise.race()- Timeout patternPromise.any()- Multiple fallback sourcesPromise.allSettled()- Batch processing
š Async Operations
Promises shine when dealing with real-world async operations like API calls, file reading, or database queries. Here are practical patterns and examples.
š” Performance Tips:
- Use parallel requests for independent data
- Use sequential requests for dependent data
- Implement retry logic for flaky operations
- Add timeouts to prevent hanging requests
- Consider batching for large operations
ā” Advanced Promise Patterns
For production applications, you'll need advanced patterns like memoization, concurrency control, cancellable promises, and state machines.
Advanced Patterns:
- Memoization - Cache promise results
- Promise Pool - Control concurrency
- Cancellable Promises - Allow cancellation
- Promise Queue - Sequential processing
Common Issues:
- Memory leaks from unhandled promises
- Uncaught promise rejections
- Promise constructor anti-pattern
- Overly nested promise chains
Best Practices:
- Always return promises from .then()
- Handle errors at appropriate levels
- Use async/await for readability
- Avoid promise constructor when possible
š Promise Anti-Patterns to Avoid
ā Don't Do This:
- Creating promises unnecessarily (promise constructor anti-pattern)
- Nesting promises instead of chaining
- Forgetting to return promises from .then() handlers
- Not handling promise rejections
- Using promises for synchronous operations
ā Do This Instead:
- Use Promise.resolve() for known values
- Chain promises with .then() returns
- Always handle errors with .catch()
- Use async/await for better readability
- Convert callbacks to promises with util.promisify()