JavaScript

What Are Promises in JavaScript?

In JavaScript, a Promise is an object that represents the eventual success or failure of an asynchronous operation. Promises help you manage operations such as…

D
DevByteTechnical Author
Published
17 min read3 views
What Are Promises in JavaScript?

When I started working with JavaScript, asynchronous code was one of the concepts that took me some time to understand. At first, I could write functions, use loops, and handle API responses, but things became confusing whenever one operation depended on another.

For example, imagine building a login system. A user enters their email and password, the application sends a request to the backend, the server validates the credentials, and then the application redirects the user to the dashboard.

These operations do not all finish immediately. The application needs to wait for the server's response before deciding what to do next.

JavaScript provides several ways to handle asynchronous operations, and Promises are one of the most important concepts to understand.

Promises help us manage operations that may finish successfully or fail in the future. They make asynchronous code easier to organize and provide a cleaner way to handle results and errors.

In this article, I'll explain JavaScript Promises from the basics, using practical examples that you can apply to real projects.

What Is a Promise in JavaScript?

A Promise is a JavaScript object that represents the eventual completion or failure of an asynchronous operation.

In simple terms, a Promise is like a commitment that a value will become available later.

For example, when you request user information from an API, the response may take a few milliseconds or several seconds. Instead of blocking the rest of your application while waiting, JavaScript allows the operation to continue asynchronously.

The Promise represents the result that will be available when the operation finishes.

A Promise can:

  • Fulfill with a result when the operation succeeds.

  • Reject with an error when the operation fails.

  • Remain pending while the operation is still in progress.

Let's start with a simple example.

const userPromise = new Promise((resolve, reject) => {
  const userExists = true;

  if (userExists) {
    resolve("User found successfully");
  } else {
    reject("User not found");
  }
});

userPromise
  .then((message) => {
    console.log(message);
  })
  .catch((error) => {
    console.error(error);
  });

Output:

User found successfully

Here, we create a Promise using the Promise constructor.

The executor function receives two important arguments:

  • resolve: Used to fulfill the Promise with a value.

  • reject: Used to reject the Promise with a reason, usually an error.

When userExists is true, we call resolve(). The success handler registered through .then() receives the result.

If userExists is false, we call reject(), and the error handler registered through .catch() handles the rejection.

This is the basic idea behind Promises.

One important detail: the executor function passed to new Promise() runs immediately. Promises do not automatically make synchronous code asynchronous. They are a mechanism for representing and handling the outcome of an operation.

Why Do We Need Promises?

To understand why Promises are useful, let's first look at a problem that developers often face when working with asynchronous operations.

Imagine that you need to fetch a user's profile and then fetch that user's orders. The second request depends on the result of the first request.

One older approach was to use callbacks.

Handling asynchronous operations with callbacks

function getUser(callback) {
  setTimeout(() => {
    console.log("User fetched");

    callback({
      id: 101,
      name: "Manjeet",
    });
  }, 1000);
}

function getOrders(userId, callback) {
  setTimeout(() => {
    console.log("Orders fetched for user:", userId);

    callback([
      { id: 1, product: "Laptop" },
      { id: 2, product: "Keyboard" },
    ]);
  }, 1000);
}

getUser((user) => {
  getOrders(user.id, (orders) => {
    console.log(orders);
  });
});

This code works, but as the number of dependent operations increases, the nesting can become difficult to maintain.

Imagine adding more steps:

  1. Fetch the user.

  2. Fetch the user's orders.

  3. Calculate the total amount.

  4. Process the payment.

  5. Generate an invoice.

  6. Send a confirmation email.

If every operation uses nested callbacks, the code can quickly become difficult to read.

Developers often call deeply nested callback structures callback hell.

Promises offer a more structured way to represent asynchronous results and connect dependent operations.

The same idea using Promises

function getUser() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        id: 101,
        name: "Manjeet",
      });
    }, 1000);
  });
}

function getOrders(userId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([
        { id: 1, product: "Laptop" },
        { id: 2, product: "Keyboard" },
      ]);
    }, 1000);
  });
}

getUser()
  .then((user) => {
    console.log("User:", user.name);

    return getOrders(user.id);
  })
  .then((orders) => {
    console.log("Orders:", orders);
  })
  .catch((error) => {
    console.error("Something went wrong:", error);
  });

Now, each step is connected through .then().

The first handler receives the user object and returns the Promise created by getOrders(). The next handler waits for that Promise to settle successfully before receiving the orders.

This makes the sequence easier to follow.

Promises do not eliminate every asynchronous problem, but they provide a foundation for writing more maintainable asynchronous JavaScript.

Understanding the Three States of a Promise

Every Promise begins in the pending state unless it is settled during its initial execution.

A Promise has three possible states:

1. Pending

A Promise is pending when its result has not been determined yet.

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Operation completed");
  }, 2000);
});

console.log(promise);

At the moment console.log() runs, the Promise is generally still pending because the timer callback has not executed.

The output in a typical browser console may look similar to:

Promise { <pending> }

The Promise will eventually fulfill with "Operation completed".

2. Fulfilled

A Promise is fulfilled when its operation has completed successfully and its result is available.

const promise = new Promise((resolve) => {
  resolve("Data fetched successfully");
});

promise.then((result) => {
  console.log(result);
});

Output:

Data fetched successfully

Calling resolve() with a normal value fulfills the Promise.

However, if resolve() receives another Promise or a thenable, the outer Promise adopts its eventual outcome instead of immediately fulfilling with that object.

3. Rejected

A Promise is rejected when the operation fails or an error is reported.

const promise = new Promise((resolve, reject) => {
  reject(new Error("Unable to fetch data"));
});

promise.catch((error) => {
  console.error(error.message);
});

Output:

Unable to fetch data

Here, the Promise is rejected with an Error object.

In real projects, I recommend rejecting Promises with Error objects rather than plain strings because they provide useful properties, including the error message and, in many environments, a stack trace.

Important: A Promise can settle only once. After it becomes fulfilled or rejected, its state cannot change again.

For example:

const promise = new Promise((resolve, reject) => {
  resolve("First result");

  reject(new Error("Second result"));
});

promise.then((result) => {
  console.log(result);
});

Output:

First result

The second call does not change the settled Promise.

How to Create a Promise in JavaScript

We can create a Promise using the built-in Promise constructor.

Its basic syntax is:

const promise = new Promise((resolve, reject) => {
  // Perform an operation

  if (operationSuccessful) {
    resolve(result);
  } else {
    reject(error);
  }
});

The names resolve and reject are conventional parameter names. You could choose different names, but using these makes the code easier for other developers to understand.

Let's build a practical example.

Suppose we want to check whether a product is available before allowing a customer to purchase it.

function checkProductAvailability(quantity) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const availableStock = 10;

      if (quantity <= availableStock) {
        resolve({
          success: true,
          message: "Product is available",
          quantity,
        });
      } else {
        reject(
          new Error("Requested quantity exceeds available stock")
        );
      }
    }, 1000);
  });
}

checkProductAvailability(5)
  .then((result) => {
    console.log(result.message);
    console.log("Quantity:", result.quantity);
  })
  .catch((error) => {
    console.error(error.message);
  });

Output:

Product is available
Quantity: 5

If we request 15 products, the Promise rejects because the available stock is only 10.

This example demonstrates how a Promise can represent the outcome of an operation that takes time.

In a production application, the stock check would normally happen through a backend API or database operation. The frontend should not be responsible for making the final decision about inventory because stock can change between the check and the purchase.

How Does .then() Work?

The .then() method is used to handle a Promise's fulfilled value.

It also returns a new Promise, which allows us to connect multiple asynchronous operations.

Let's look at a simple example.

const promise = Promise.resolve(10);

promise
  .then((number) => {
    console.log(number);

    return number * 2;
  })
  .then((result) => {
    console.log(result);

    return result + 5;
  })
  .then((finalResult) => {
    console.log(finalResult);
  });

Output:

10
20
25

Here's what happens:

  1. The first handler receives 10.

  2. It returns 20.

  3. The second handler receives 20 and returns 25.

  4. The final handler receives 25.

The important concept here is Promise chaining.

Each .then() returns a new Promise. If a handler returns a normal value, the next Promise fulfills with that value. If the handler returns another Promise, the chain waits for its outcome.

This is particularly useful when the result of one operation is needed by the next operation.

For example:

function getProductPrice() {
  return Promise.resolve(1000);
}

function applyDiscount(price) {
  return Promise.resolve(price - 100);
}

getProductPrice()
  .then((price) => {
    return applyDiscount(price);
  })
  .then((finalPrice) => {
    console.log("Final price:", finalPrice);
  })
  .catch((error) => {
    console.error(error.message);
  });

Output:

Final price: 900

Notice that we return applyDiscount(price) from the first .then().

Without that return, the next handler would not receive the discount operation's result through the chain.

This is one of the most common mistakes when working with Promise chains.

How to Handle Errors with .catch()

Asynchronous operations can fail for many reasons. An API might return an error, a database connection might fail, or a file might not exist.

The .catch() method provides a way to handle Promise rejections.

function fetchUser() {
  return new Promise((resolve, reject) => {
    const isServerAvailable = false;

    if (isServerAvailable) {
      resolve({
        id: 101,
        name: "Manjeet",
      });
    } else {
      reject(new Error("Server is unavailable"));
    }
  });
}

fetchUser()
  .then((user) => {
    console.log(user);
  })
  .catch((error) => {
    console.error("Request failed:", error.message);
  });

Output:

Request failed: Server is unavailable

The rejection is handled by .catch().

Another useful detail is that .catch() can handle errors thrown inside earlier .then() handlers.

Promise.resolve({ name: "Manjeet" })
  .then((user) => {
    if (!user.email) {
      throw new Error("Email address is missing");
    }

    return user;
  })
  .then((user) => {
    console.log(user);
  })
  .catch((error) => {
    console.error(error.message);
  });

Output:

Email address is missing

Throwing an error inside a Promise handler rejects the Promise returned by that handler. The rejection then travels down the chain until a suitable rejection handler catches it.

This means you can handle errors from multiple steps in a single .catch().

However, avoid catching an error and silently ignoring it. If the application cannot recover from a failure, handle it appropriately or rethrow the error so that the calling code knows something went wrong.

What Is .finally() Used For?

The .finally() method runs when a Promise settles, whether it fulfills or rejects.

It is useful for cleanup tasks that should happen regardless of the result.

For example, when a user submits a form, we might show a loading indicator while the request is running. After the request finishes, we want to hide the indicator whether the request succeeds or fails.

function submitForm() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const success = true;

      if (success) {
        resolve("Form submitted successfully");
      } else {
        reject(new Error("Form submission failed"));
      }
    }, 2000);
  });
}

console.log("Submitting form...");

submitForm()
  .then((message) => {
    console.log(message);
  })
  .catch((error) => {
    console.error(error.message);
  })
  .finally(() => {
    console.log("Loading indicator removed");
  });

Output:

Submitting form...
Form submitted successfully
Loading indicator removed

Even if we change success to false, the finally() handler will still run.

In React applications, the same idea can be used to reset loading state after a request completes. With async/await, developers commonly achieve this by placing cleanup code inside a finally block.

One detail worth remembering is that .finally() normally preserves the original fulfillment value or rejection unless its callback throws an error or returns a rejected Promise.

Using Promises with the Fetch API

So far, we've created Promises manually to understand how they work. In actual applications, you will often work with APIs that already return Promises.

The browser's Fetch API is one example.

Imagine that we need to fetch a list of users from an API.

fetch("https://jsonplaceholder.typicode.com/users")
  .then((response) => {
    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }

    return response.json();
  })
  .then((users) => {
    console.log("Users:", users);
  })
  .catch((error) => {
    console.error("Failed to fetch users:", error.message);
  });

Let's understand this step by step.

Step 1: Send the request

fetch("https://jsonplaceholder.typicode.com/users")

The fetch() function returns a Promise that fulfills with a Response object when a response is received.

Step 2: Check the HTTP response

if (!response.ok) {
  throw new Error(`HTTP error: ${response.status}`);
}

An important point about Fetch is that it generally does not reject its Promise just because the server responds with an HTTP error status such as 404 or 500.

That is why we check response.ok ourselves.

Step 3: Parse the response body

return response.json();

The response.json() method also returns a Promise because reading and parsing the response body is asynchronous.

We return that Promise so that the next .then() receives the parsed data.

Step 4: Handle the result or error

.then((users) => {
  console.log("Users:", users);
})
.catch((error) => {
  console.error(error.message);
});

The final handler receives the parsed user data. If a network failure occurs or one of the preceding handlers throws an error, the rejection can be handled by .catch().

This pattern is common in frontend applications, including React and Next.js projects.

Converting Callback-Based Functions into Promises

Sometimes you will work with older APIs or libraries that use callbacks instead of Promises.

For example:

function getUserData(callback) {
  setTimeout(() => {
    const user = {
      id: 101,
      name: "Manjeet",
    };

    callback(null, user);
  }, 1000);
}

getUserData((error, user) => {
  if (error) {
    console.error(error);
    return;
  }

  console.log(user);
});

Here, the callback receives two arguments: an error and a result.

We can wrap this function in a Promise.

function getUserDataPromise() {
  return new Promise((resolve, reject) => {
    getUserData((error, user) => {
      if (error) {
        reject(error);
      } else {
        resolve(user);
      }
    });
  });
}

getUserDataPromise()
  .then((user) => {
    console.log("User:", user);
  })
  .catch((error) => {
    console.error("Error:", error.message);
  });

Now the function can be used with .then(), .catch(), or async/await.

In Node.js, the built-in node:util module provides promisify() for converting compatible error-first callback functions into Promise-returning functions.

For example:

const fs = require("node:fs");
const { promisify } = require("node:util");

const readFile = promisify(fs.readFile);

readFile("example.txt", "utf8")
  .then((content) => {
    console.log(content);
  })
  .catch((error) => {
    console.error("Unable to read file:", error.message);
  });

For modern Node.js code, many APIs already provide Promise-based alternatives, such as node:fs/promises. Whenever a native Promise-based API is available, it is often the simplest choice.

What Is the Difference Between a Promise and a Callback?

Both callbacks and Promises can be used to handle asynchronous operations, but they organize the result differently.

Feature

Callback

Promise

Basic approach

Pass a function to another function

Work with an object representing an eventual result

Error handling

Often uses an error-first callback convention

Uses rejection handlers such as .catch()

Chaining

Can require nested callbacks

Supports chaining with .then()

Return value

Depends on the function's implementation

.then(), .catch(), and .finally() return Promises

Composition

Requires manual coordination in many cases

Supports built-in methods such as Promise.all()

Modern syntax

Callback-based functions can still be useful

Can be consumed with async/await

Neither approach is automatically better in every situation. Callbacks remain useful for event listeners and APIs that naturally work with callback functions.

However, Promises are generally more convenient when working with asynchronous operations that produce a result and need to be chained, composed, or handled with structured error propagation.

How Promises Work with JavaScript's Event Loop

One of the most interesting things about Promises is how their handlers are scheduled.

JavaScript executes synchronous code first. Promise handlers registered through .then(), .catch(), or .finally() run asynchronously through the Promise job mechanism, commonly described using the microtask queue in browsers and Node.js.

Let's look at a simple example.

console.log("First");

Promise.resolve().then(() => {
  console.log("Second");
});

console.log("Third");

Output:

First
Third
Second

Why does this happen?

First, JavaScript executes:

console.log("First");

Next, it registers a handler for the already-fulfilled Promise. The handler does not execute immediately; it is scheduled to run after the current synchronous execution finishes.

JavaScript then executes:

console.log("Third");

Once the current synchronous code has finished, the scheduled Promise handler runs.

That is why "Second" appears last.

Now compare this with a timer.

console.log("Start");

setTimeout(() => {
  console.log("Timer callback");
}, 0);

Promise.resolve().then(() => {
  console.log("Promise callback");
});

console.log("End");

In a typical browser environment, the output is:

Start
End
Promise callback
Timer callback

The timer uses a task scheduled by setTimeout(), while the Promise handler is scheduled as a microtask. After the synchronous code finishes, queued microtasks are processed before the next timer task runs.

The 0 in setTimeout() does not mean the callback executes immediately.

Understanding this behavior helps explain why Promise handlers sometimes run later than expected, even when the Promise is already fulfilled.

Common Mistakes When Working with Promises

Promises are straightforward once you understand the fundamentals, but a few mistakes appear frequently in real projects.

1. Forgetting to return a Promise

Consider this example:

function getUser() {
  return Promise.resolve({
    id: 101,
    name: "Manjeet",
  });
}

getUser()
  .then((user) => {
    getUserOrders(user.id);
  })
  .then((orders) => {
    console.log(orders);
  });

The problem is that getUserOrders() is called without returning its Promise.

The next .then() therefore does not wait for the orders request, and orders will not contain the result of that request.

The corrected version is:

getUser()
  .then((user) => {
    return getUserOrders(user.id);
  })
  .then((orders) => {
    console.log(orders);
  })
  .catch((error) => {
    console.error(error);
  });

Returning the Promise connects the asynchronous operation to the chain.

2. Assuming every error is caught automatically

A .catch() handles rejections that reach its position in the Promise chain. But if you start an unrelated Promise and fail to return or otherwise handle it, the outer chain might not catch its rejection.

For example:

Promise.resolve()
  .then(() => {
    Promise.reject(new Error("Request failed"));
  })
  .catch((error) => {
    console.error("Caught:", error.message);
  });

The rejection created inside the handler is not returned. Therefore, the outer chain does not adopt that rejection, and the .catch() shown here does not handle it.

A better version is:

Promise.resolve()
  .then(() => {
    return Promise.reject(new Error("Request failed"));
  })
  .catch((error) => {
    console.error("Caught:", error.message);
  });

Now the rejection becomes part of the chain and is handled correctly.

3. Thinking that creating a Promise makes an operation asynchronous

Consider this example:

const promise = new Promise((resolve) => {
  console.log("Executor runs immediately");

  resolve("Completed");
});

promise.then((result) => {
  console.log(result);
});

console.log("End");

Output:

Executor runs immediately
End
Completed

The executor runs immediately when the Promise is constructed. The .then() handler runs later.

Creating a Promise does not automatically move synchronous work to the background. If you perform an expensive calculation inside the executor, it can still block the JavaScript thread.

4. Forgetting to handle failures

A Promise rejection that has no appropriate rejection handler can result in an unhandled rejection warning or error.

For application code, make sure you have a clear strategy for handling failures, whether that means recovering locally, showing an error message, logging the problem, or passing the rejection to the calling function.

When Should You Use Promises?

Promises are useful whenever an operation produces a result asynchronously.

Common examples include:

  • Fetching data from a REST API.

  • Reading files in Node.js.

  • Querying a database through a Promise-based driver.

  • Uploading files to cloud storage.

  • Waiting for an authentication request.

  • Performing background network operations.

  • Connecting multiple asynchronous steps in a workflow.

For example, in a Node.js backend, you might retrieve a user from MongoDB and then fetch related information. In a React application, you might request product data and display it after the request finishes.

In these situations, Promises provide a consistent way to work with eventual results and failures.

You do not need to manually create a Promise every time you perform an asynchronous operation. Many APIs already return Promises, so you can use those directly.

For example:

async function getProducts() {
  const response = await fetch(
    "https://jsonplaceholder.typicode.com/posts"
  );

  if (!response.ok) {
    throw new Error(`HTTP error: ${response.status}`);
  }

  return response.json();
}

getProducts()
  .then((products) => {
    console.log("Products:", products);
  })
  .catch((error) => {
    console.error("Unable to fetch products:", error.message);
  });

This example uses async/await, which is built on Promises. The async function returns a Promise, and await lets us write Promise-based code in a more sequential style.

The underlying asynchronous operation is still represented by a Promise.

Conclusion

Promises are a fundamental part of modern JavaScript. They provide a structured way to handle asynchronous operations, represent successful results or failures, and connect dependent tasks without deeply nested callbacks.

The most important concepts to remember are:

  • A Promise represents the eventual outcome of an operation.

  • A Promise can be pending, fulfilled, or rejected.

  • .then() handles successful results and supports chaining.

  • .catch() handles rejections and errors propagated through a Promise chain.

  • .finally() runs after settlement and is useful for cleanup.

  • Promise handlers are scheduled asynchronously, even when the Promise is already fulfilled.

  • Returning Promises from handlers ensures that dependent operations are connected correctly.

  • async/await provides another way to consume Promises with a more sequential coding style.

If you're building applications with Node.js, React, Next.js, or any other modern JavaScript framework, understanding Promises will make it much easier to work with APIs, databases, and other asynchronous operations.

My recommendation is to practise these concepts with small examples first. Try fetching data from an API, handling a failed request, chaining two dependent operations, and converting a callback-based function into a Promise.

Once you understand how Promises behave, asynchronous JavaScript becomes much easier to read, debug, and maintain.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘