There are no items in your cart
Add More
Add More
Item Details | Price |
---|
In this article, you will learn about JavaScript promises, what they are, and how to use them effectively.
• Yash Gupta • Feb 19, 2025 • 8 mins read
A Promise is an object that represents a value that may be available in the future, either resolving successfully or being rejected.
Since JavaScript is a single-threaded language with one call stack, it executes code synchronously by default.
Promises offer a cleaner way to handle asynchronous operations, providing better error management compared to callbacks. In short, Promises enable asynchronous behavior in JavaScript, making it more flexible and powerful. 🚀
Let's understand this with an example:
Suppose that you promise to lose 10 kgs by next month.
You don’t know if you will spend your time and effort to lose weight until next month. You can either be losing weight or not.
Promise has three possible states:
A promise starts in the pending state, which indicates that it has yet to be completed. It ends in either a resolved/fulfilled (successful) or a rejected (failed) state.
To create a promise in JavaScript, you use the Promise constructor as shown below:
const prom = new Promise((resolve, reject) => {const result = 8 + 7;result === 15resolve("This resolve should come in the then block")reject("This reject should come in the catch block");});prom.then(msg => console.log("then block -->", msg)).catch(msg => console.log("catch block -->", msg));
When we run the above code we get the following output:
then block --> This resolve should come in the then block
'''catch block --> This reject should come in the catch block'''
// Simulated database of usersconst users = [{ name: "Alice", age: 25 },{ name: "Bob", age: 30 },{ name: "Charlie", age: 28 },];// Function to add a new userconst addUser = (user) => {return new Promise((resolve, reject) => {setTimeout(() => {let error;if (user && user.name && user.age) {error = false;users.push(user); // Adding the new user to the database} else {error = true;}error ? reject("Error: Invalid user data") : resolve();}, 2000);});};// Function to fetch all usersconst fetchUsers = () => {setTimeout(() => {console.log("User List:");users.forEach((user) => console.log(`${user.name}, Age: ${user.age}`));}, 1000);};// Adding a new user and then fetching all usersaddUser({ name: "David", age: 32 }).then(fetchUsers) // If successful, fetch all users.catch((error) => console.log(error)); // Log error if anyconsole.log("Executing other lines of code...\n");
Take a look at the following code:
addUser({ name: "David", age: 32 }).then(fetchUsers) // If the user is added successfully, fetch all users.catch((error) => console.log(error)); // If an error occurs, log the error message
Output of the above code:
In simple terms, a Promise is an object that eventually either resolves or rejects, returning a response based on the conditions defined inside it.
If you’ve ever used fetch() or axios() to retrieve a JSON response from an external API—like fetching weather data from OpenWeatherMap (see image below)—you’ve already been working with Promises! 🚀
Thank you for reading this!
I hope this post will help you in your journey. Keep learning!
Yash Gupta
I am passionate about tech and coding. I share expert insights on Test Automation (Selenium, Cypress, Playwright), API Automation, JavaScript, Python, Svelte, Vue.js, ReactJS, Angular, Flutter, and more. Stay updated with the latest trends! 🚀