JavaScript Promises | Lecture 9
JavaScript
Promises are a way to handle asynchronous operations. A promise
represents a value that might be available now, in the future, or never. They
are used to avoid callback hell and make asynchronous code easier to read and
manage.
Key States of a Promise:
- Pending: The promise is still
pending and hasn't been resolved or rejected.
- Fulfilled: The promise was completed
successfully.
- Rejected: The promise failed.
Basic Syntax
const promise = new Promise((resolve, reject) =>
{
//
asynchronous operation
if
(successCondition) {
resolve("Success!"); // When operation succeeds
} else {
reject("Error!"); // When operation fails
}
});
Handling Promises
- then(): Executes when the promise
is resolved.
- catch(): Executes when the promise
is rejected.
- finally(): Executes after the promise
is settled (either resolved or rejected).
Examples
Example 1: A Simple Promise
const myPromise = new Promise((resolve, reject)
=> {
let success
= true;
if
(success) {
resolve("Promise resolved successfully!");
} else {
reject("Promise rejected.");
}
});
myPromise
.then((message) => {
console.log("Success:", message);
})
.catch((error) => {
console.log("Error:", error);
})
.finally(()
=> {
console.log("Promise operation completed.");
});
Example 2: Simulating Asynchronous Operations
(e.g., API Call)
const fetchData = new Promise((resolve, reject)
=> {
setTimeout(() => {
let data
= { id: 1, name: "John Doe" };
resolve(data); // Simulating a successful API response
}, 2000);
});
fetchData
.then((data) => {
console.log("Fetched Data:", data);
})
.catch((error) => {
console.error("Error fetching data:", error);
});
Example 3: Using Promise.all()
const promise1 = Promise.resolve(10);
const promise2 = Promise.resolve(20);
const promise3 = Promise.resolve(30);
Promise.all([promise1, promise2, promise3])
.then((results) => {
console.log("Results:", results); // [10, 20, 30]
})
.catch((error) => {
console.error("Error in one of the promises:", error);
});
Example 4: Using Promise.race()
const promise1 = new Promise((resolve) =>
setTimeout(() => resolve("First!"), 1000));
const promise2 = new Promise((resolve) =>
setTimeout(() => resolve("Second!"), 2000));
Promise.race([promise1, promise2])
.then((result) => {
console.log("First to complete:", result); //
"First!"
})
.catch((error) => {
console.error("Error:", error);
});
Example 5: Chaining Promises
const step1 = () => Promise.resolve("Step 1
completed");
const step2 = (prev) =>
Promise.resolve(`${prev}, Step 2 completed`);
const step3 = (prev) =>
Promise.resolve(`${prev}, Step 3 completed`);
step1()
.then(step2)
.then(step3)
.then((result) => {
console.log("Final Result:", result);
});
Promises are powerful tools for managing
asynchronous code, and when used with modern syntax like async/await, they make code even more readable and
maintainable.
Comments
Post a Comment