By the end of this lesson, you will understand JavaScript promises and how to use them effectively in your code.
JavaScript async operations are objects that represent the eventual completion or failure of an asynchronous task. You can think of a promise like ordering a pizza. You place your order, which is the request. Then, the restaurant tells you they will deliver it soon, which is the promise. You can either receive the pizza, meaning the promise is fulfilled, or you could be informed that the order failed, indicating rejection.
In programming, handling async tasks can be tricky. JavaScript makes this easier. For example, instead of using callback functions that may lead to callback hell, you can manage async flow in a more structured way with promises. Therefore, this leads to cleaner and more maintainable code.
File: pizzaOrder.js
const orderPizza = new Promise((resolve, reject) => {
const isPizzaReady = true;
if (isPizzaReady) {
resolve("Your pizza is ready!");
} else {
reject("Sorry, your order failed.");
}
});
orderPizza
.then(message => console.log(message))
.catch(error => console.log(error));
Your pizza is ready!
In this code, we create a new promise. It checks if the pizza is ready. If it is, we call resolve to indicate success. If not, we call reject to signify failure. The then method will execute if the promise is resolved, while the catch method helps manage any errors in case it fails.
Now, let’s practice! Create a promise that simulates fetching user data. The promise should either resolve with user data or reject with an error message. This task helps reinforce your understanding of how promises work in JavaScript.
File: fetchUserData.js
const fetchUserData = new Promise((resolve, reject) => {
const userDataAvailable = true;
if (userDataAvailable) {
resolve({ name: "John", age: 25 });
} else {
reject("User data not found.");
}
});
fetchUserData
.then(data => console.log(data))
.catch(error => console.log(error));
{ name: "John", age: 25 }
catch method to handle possible errors.catch method.To dive deeper into the basics of JavaScript, check out our lesson on What Is JavaScript? This lesson provides valuable context on JavaScript fundamentals.