Async & Promisesmedium
Explain how Promises work in JavaScript.
Describe the lifecycle of a Promise and how it handles asynchronous operations, including pending, fulfilled, and rejected states.
Answer
Promises represent the eventual completion (or failure) of an asynchronous operation. Lifecycle includes:
- Pending: The initial state; neither fulfilled nor rejected.
- Fulfilled: The operation completed successfully, resolving to a value.
- Rejected: The operation failed, resulting in a reason (error).
They enable chaining with .then() and handle errors with .catch(), allowing for cleaner, more manageable asynchronous code.