JavaScript Promises

JavaScript Promises
In JavaScript Promises is an object representing the eventual completion or failure of an asynchronous operation.
It allows handling async tasks more cleanly than callbacks.
Promise States
| State | Description |
|---|---|
| Pending | Initial state, operation not completed yet |
| Fulfilled | Operation completed successfully |
| Rejected | Operation failed |
Creating a Promise
Consuming a Promise
Example: Simulate Async Task
Chaining Promises
You can chain .then() to perform multiple steps sequentially:
Promise.all()
Promise.all() runs multiple promises in parallel and waits for all to complete.
Promise.race()
Promise.race() returns the result of the first promise to settle.
Best Practices
Always handle errors with
.catch()Chain promises instead of nesting callbacks
Use
Promise.all()for parallel async operationsConsider using
async/awaitfor cleaner syntax
Summary Table
| Concept | Method |
|---|---|
| Create Promise | new Promise((resolve, reject) => {}) |
| Resolve | resolve(value) |
| Reject | reject(error) |
| Handle success | .then(result => {}) |
| Handle error | .catch(error => {}) |
| Run multiple | Promise.all() |
| First completed | Promise.race() |
