Promises in JavaScript
Key Concepts
Promises in JavaScript are used to handle asynchronous operations. The key concepts include:
- Creating a Promise
- Promise States
- Chaining Promises
- Error Handling
Creating a Promise
A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
const myPromise = new Promise((resolve, reject) => { setTimeout(() => { const success = true; if (success) { resolve("Operation successful!"); } else { reject("Operation failed!"); } }, 1000); });
Promise States
A Promise can be in one of three states:
- Pending: The initial state, neither fulfilled nor rejected.
- Fulfilled: The operation completed successfully.
- Rejected: The operation failed.
myPromise .then((message) => { console.log(message); // Output: Operation successful! }) .catch((error) => { console.log(error); // Output: Operation failed! });
Chaining Promises
Promises can be chained together to handle a sequence of asynchronous operations. Each then
method returns a new Promise, allowing for sequential execution.
myPromise .then((message) => { console.log(message); return "Next step"; }) .then((nextMessage) => { console.log(nextMessage); // Output: Next step }) .catch((error) => { console.log(error); });
Error Handling
Error handling in Promises is done using the catch
method. This method is used to handle any errors that occur during the execution of the Promise chain.
myPromise .then((message) => { console.log(message); throw new Error("Something went wrong"); }) .catch((error) => { console.log(error.message); // Output: Something went wrong });
Examples and Analogies
Imagine a Promise as a restaurant order:
- Creating a Promise: Placing an order at the restaurant.
- Promise States: The order can be pending (waiting to be prepared), fulfilled (ready to be served), or rejected (the dish is unavailable).
- Chaining Promises: Ordering appetizers, main course, and dessert in sequence.
- Error Handling: Handling the situation if the dish you ordered is not available.
© 2024 Ahmed Baheeg Khorshid. All rights reserved.