Welcome, JavaScript adventurers! In this chapter, we embark on a journey into the realm of promises. Promises provide a more structured and readable way to handle asynchronous operations compared to callback functions. Buckle up as we explore the fundamentals, practical applications, and advanced considerations of promises in JavaScript.
.then function) when the food (result) is ready, or letting you know if there’s an issue (calling your .catch function).
function getUserData(userId) {
return new Promise((resolve, reject) => {
// Simulate fetching data from a server (replace with actual fetch API call)
const userData = { name: "Alice", age: 30 };
setTimeout(() => {
if (userData) {
resolve(userData); // Resolve the promise with the data (like bringing the food)
} else {
reject(new Error("Failed to fetch user data")); // Reject the promise with an error (like informing about a missing ingredient)
}
}, 1000);
});
}
getUserData(123)
.then(data => {
console.log(data); // Output: { name: "Alice", age: 30 } (after 1 second)
})
.catch(error => {
console.error(error); // Handle errors (like informing the customer about the issue)
});
console.log("This line executes before user data is retrieved");
getUserData function now returns a promise.resolve function is called with the data when the operation finishes successfully..then method is used to handle the successful outcome (data retrieval)..catch method is used to handle errors (promise rejection).console.log statement outside the promise chain executes immediately..then and .catch)..catch..then for handling multiple asynchronous operations sequentially.
function getUserPosts(userId) {
return new Promise((resolve, reject) => {
// Simulate fetching posts from a server (replace with actual fetch API call)
const posts = [
{ title: "Post 1", content: "..." },
{ title: "Post 2", content: "..." },
];
setTimeout(() => {
resolve(posts);
}, 1000);
});
}
getUserData(123)
.then(data => {
console.log("User data:", data);
return getUserPosts(data.id); // Chain to another promise (get posts for the user)
})
.then(posts => {
console.log("User posts:", posts);
})
.catch(error => {
console.error(error);
});
.then..then retrieves user data and then returns another promise to get the user’s posts..then receives the result of the previous promise in the chain.Promise.all: Executes multiple promises concurrently and resolves only when all of them are settled (completed or rejected).Promise.race: Executes multiple promises concurrently and resolves with the result (or rejection) of the first promise to settle.Promise.all: Executes multiple promises concurrently and resolves only when all of them are settled (completed or rejected). Promise.race: Executes multiple promises concurrently and resolves with the result (or rejection) of the first promise to settle. Happy coding !❤️
