Promises in JavaScript

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

What is Promise in JavaScript?

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. 🚀

Working of Promise:

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:

  • Pending: You don’t know if you will lose 10kg by the next month.
  • Resolved/Fulfilled: You lost 10kgs by the next month.
  • Rejected: You don't lose weight at all.

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.

Let's Write a Simple Code:

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 === 15
resolve("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

As, 8 + 7 = 15 the a = 15 so it will execute if(){} block and it will resolve the promise. If we change a = 8 + 7 to a = 5 + 1 and keep the rest of the code the same we will get the following output as it will execute the else{} block and it will reject the promise.

'''catch block --> This reject should come in the catch block'''

Let's Write a Simple Code:

// Simulated database of users
const users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 28 },
];

// Function to add a new user
const 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 users
const 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 users
addUser({ name: "David", age: 32 })
.then(fetchUsers) // If successful, fetch all users
.catch((error) => console.log(error)); // Log error if any

console.log("Executing other lines of code...\n");

  • The addUser() function adds a new user after 2 seconds.
  • The fetchUsers() function fetches and logs all users after 1 second.
  • If the user data is valid, it is added, and fetchUsers() runs.
  • If there’s an error (e.g., missing name or age), it rejects the promise and logs an error message.

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

  • addUser({ name: "David", age: 32 }) attempts to add a new user.
  • If successful, .then(fetchUsers) is called to display all users.
  • If there’s an error (e.g., missing user details), .catch() logs the error.
  • Output of the above code:

    Closing Thoughts:

    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! 🚀