Sitemap

JavaScript Promises

14 min readApr 23, 2026

--

JavaScript Promises Explained for Beginners

Press enter or click to view image in full size

JavaScript promises are one of those topics that feel confusing at first, but once they click, they make asynchronous programming much easier to understand. Many beginners struggle because promises are often introduced with technical words like “resolve,” “reject,” and “asynchronous flow” before the real problem is explained. So in this blog, we will go slowly, build the idea from the ground up, and understand why promises exist at all.

Think of a promise like ordering food online. You place the order now, but you do not get the food immediately. Instead, you receive a confirmation that your order is being processed. After some time, one of two things happens: either the food arrives successfully, or the order gets cancelled. That waiting period is the key idea behind promises in JavaScript. A promise represents a value that is not available right now, but may become available later.

Promises are JavaScript’s cleaner way of handling future results. They help organize code that takes time, such as loading data from an API, reading a file, waiting for a timer, or performing background work. Before promises became common, callbacks were heavily used for this kind of work, but large callback-based code quickly became messy and hard to follow. Promises improved readability, structure, and error handling.

Let us understand this deeply, step by step.

1. What Problem Promises Solve

To understand promises, we first need to understand the problem they were created to solve.

JavaScript runs code line by line in a single main thread for most normal tasks. That means if one operation takes a long time, it can delay everything else. But in real applications, many operations are slow by nature. For example, fetching user data from a server takes time. Reading from a database takes time. Waiting 2 seconds with a timer takes time. Downloading an image takes time. These are not instant tasks.

Now imagine if JavaScript stopped the whole program every time it had to wait for something slow. Your webpage would freeze. Buttons would stop working. The screen might look stuck. That would be a terrible user experience. So JavaScript uses asynchronous behavior for such tasks. It starts the work, allows the rest of the code to continue, and later handles the result when it arrives.

Before promises, callbacks were the common solution. A callback is simply a function passed into another function, so that it can run later when the work is done. This works for simple cases, but becomes difficult when you have multiple dependent steps.

For example, imagine this flow:

  • first fetch user data
  • then fetch that user’s orders
  • then fetch details for each order
  • then update the UI
  • handle errors at every step

With callbacks, this can become deeply nested. One function inside another, then another, then another. This is often called callback hell. The code starts drifting to the right, becomes difficult to read, and error handling becomes harder to manage.

Here is a simple callback-style example:

getUser(function(user) {
getOrders(user.id, function(orders) {
getOrderDetails(orders[0], function(details) {
console.log(details);
});
});
});

Even this small example already feels harder to follow than straight-line code. As more steps get added, the structure becomes more confusing.

Promises solve this by giving us a better way to represent a future result. Instead of immediately demanding the final value, we work with an object that says:

“I do not have the result yet, but I will settle later.”

That is the promise.

With promises, we can write the same type of logic in a more organized way:

getUser()
.then(user => getOrders(user.id))
.then(orders => getOrderDetails(orders[0]))
.then(details => console.log(details))
.catch(error => console.error(error));

This version is easier to read because it flows downward in a cleaner sequence. Each step waits for the previous one to finish. Error handling is also more centralized.

So the real problem promises solve is not just “asynchronous code.” They solve the problem of managing asynchronous code in a readable, maintainable, and reliable way.

Why this matters in real systems

In real applications, asynchronous work is everywhere. Login systems, payment processing, product search, chat messages, notifications, image uploads, dashboard data loading — all of these involve delayed results. If the code handling these flows becomes messy, bugs become common and maintenance becomes painful. Promises help developers build these flows in a cleaner and more predictable way.

2. Promises as a Future Value

The best way to understand a promise is to treat it as a future value.

When you normally write JavaScript like this:

let result = 10 + 20;
console.log(result);

the value is available immediately. result becomes 30 right away.

But in asynchronous work, the value is not ready immediately. For example:

let data = fetch("https://api.example.com/users");
console.log(data);

At that exact moment, the actual server response has not arrived yet. So fetch() does not return the final data instantly. Instead, it returns a promise.

That promise is like a placeholder. It is not the data itself. It is a wrapper representing the future result of that data.

You can think of it like this:

  • normal value = available now
  • promise = value that will arrive later

This idea is extremely important. Beginners often get confused because they expect a promise to behave like a finished value. But a promise is more like a ticket you hold while waiting.

For example:

let response = fetch("https://api.example.com/users");
console.log(response);

You will not see the final JSON data directly. You will see a promise object. That is because JavaScript is saying: “The network request has started, but it has not finished yet.”

So promises help us work with delayed results without freezing the program.

A promise gives structure to waiting. Instead of writing random nested callbacks, we now have a standard object that represents eventual success or failure.

This is powerful because almost every modern JavaScript API that deals with async work uses promises. fetch() uses promises. Many database libraries use promises. Modern frameworks depend heavily on promise-based thinking. Later, async/await is built directly on top of promises. So if you understand promises well, a huge part of modern JavaScript becomes much easier.

Real-world analogy

Imagine you apply for a passport renewal. You do not receive the passport immediately. Instead, you receive an acknowledgment that your request has been accepted and is under processing. Later:

  • if all goes well, you receive the passport
  • if something goes wrong, the request is rejected

That acknowledgment behaves like a promise. It is not the final passport, but it represents a future result.

3. Promise States: Pending, Fulfilled, Rejected

Every promise has a state. This state tells us what stage the promise is in.

There are three main promise states:

  • Pending
  • Fulfilled
  • Rejected

Let us understand each one clearly.

Pending

A promise starts in the pending state. This means the operation is still in progress. Nothing has completed yet. The promise is waiting.

For example, if you start a network request, the promise remains pending until the server responds. During this time, JavaScript continues running other code.

Pending means:

  • the work has started
  • no final result yet
  • no success yet
  • no failure yet

This is the “waiting” stage.

Fulfilled

A promise becomes fulfilled when the operation completes successfully.

This means:

  • the async task finished
  • the expected result is available
  • the success value can now be used

For example, if you requested user data from an API and the data arrived successfully, the promise becomes fulfilled with that data.

Fulfilled is sometimes casually called “resolved successfully,” though technically “resolved” has a slightly broader meaning in the promise specification. For beginner learning, you can safely think of fulfilled as success.

Rejected

A promise becomes rejected when something goes wrong.

This means:

  • the task failed
  • an error happened
  • the promise now holds a failure reason

For example:

  • server not responding
  • invalid input
  • file not found
  • network request failed
  • manual rejection inside code

Rejected promises allow us to handle failures in a structured way instead of crashing unpredictably.

Very important rule: a promise settles only once

A promise begins as pending, and then it settles into either:

  • fulfilled
  • rejected

After that, it cannot change again.

So:

  • pending → fulfilled
  • pending → rejected

But never:

  • fulfilled → rejected
  • rejected → fulfilled

This one-time settlement makes promises predictable.

Example

let myPromise = new Promise((resolve, reject) => {
let success = true;

if (success) {
resolve("Task completed successfully");
} else {
reject("Task failed");
}
});

If success is true, the promise is fulfilled. If false, it is rejected.

Why this matters in real systems

In real applications, predictability matters a lot. When dealing with user authentication, payments, file uploads, or messaging systems, you want a clear result. Either the operation succeeded, or it failed. Promises provide that clean state model, making it easier to reason about application behavior.

4. Basic Promise Lifecycle

Now let us understand the full journey of a promise from start to finish.

A promise lifecycle usually looks like this:

  1. Promise is created
  2. It starts in pending state
  3. Async work happens
  4. It becomes fulfilled or rejected
  5. Attached handlers run

This lifecycle is easier to understand with code.

let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data received");
}, 2000);
});

Let us break this down slowly.

Step 1: new Promise(...)

This creates a new promise object.

The Promise constructor takes a function. That function is automatically called by JavaScript. It receives two parameters:

  • resolve
  • reject

These are also functions.

Step 2: pending state starts immediately

As soon as the promise is created, it starts in the pending state. The asynchronous task begins.

In this example, setTimeout starts a 2-second wait.

Step 3: async task completes

After 2 seconds, the callback inside setTimeout runs.

Step 4: resolve or reject

Here we call:

resolve("Data received");

This changes the promise from pending to fulfilled.

If instead we called:

reject("Something went wrong");

then it would change to rejected.

Step 5: handlers react

To use the result, we attach handlers like .then() and .catch().

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

If the promise fulfills, .then() runs.
If the promise rejects, .catch() runs.

Full example

let promise = new Promise((resolve, reject) => {
let serverResponse = true;

setTimeout(() => {
if (serverResponse) {
resolve("User data loaded");
} else {
reject("Failed to load user data");
}
}, 2000);
});

promise
.then(data => {
console.log("Success:", data);
})
.catch(error => {
console.log("Error:", error);
});

What happens here

  • promise is created
  • it starts pending
  • timer waits for 2 seconds
  • if serverResponse is true, promise fulfills
  • if false, promise rejects
  • correct handler runs

This is the promise lifecycle in action.

Why this matters in real systems

This same lifecycle appears in real features like:

  • loading user profile data
  • checking payment status
  • uploading an image
  • verifying login credentials
  • fetching product reviews

Understanding the lifecycle makes async code much less mysterious. Once you know when a promise starts, waits, settles, and triggers handlers, you can debug async code much more confidently.

5. Handling Success and Failure

One of the best features of promises is that they provide a structured way to handle both success and failure.

Get Swagatika Sahoo’s stories in your inbox

Join Medium for free to get updates from this writer.

In old callback-based code, success and error logic often got mixed together in inconsistent ways. Promises give us a cleaner pattern.

Handling success with .then()

.then() is used when a promise is fulfilled.

let promise = Promise.resolve("File loaded successfully");

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

When the promise succeeds, the value is passed into the function inside .then().

Handling failure with .catch()

.catch() is used when a promise is rejected.

let promise = Promise.reject("File not found");

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

If the promise fails, the rejection reason is passed into .catch().

Handling both together

let myPromise = new Promise((resolve, reject) => {
let isSuccess = false;

if (isSuccess) {
resolve("Operation successful");
} else {
reject("Operation failed");
}
});

myPromise
.then(result => {
console.log("Success:", result);
})
.catch(error => {
console.log("Failure:", error);
});

This is a very common promise pattern.

Why failure handling is important

Beginners sometimes focus only on the success path. But in real applications, errors are normal. Networks fail. Servers time out. Users enter wrong data. Files may be missing. Good developers write code that handles failures gracefully.

Promises encourage that mindset by making error handling part of the flow.

.finally() concept

Promises also support .finally(), which runs whether the promise succeeds or fails.

myPromise
.then(result => {
console.log(result);
})
.catch(error => {
console.log(error);
})
.finally(() => {
console.log("Promise finished");
});

This is useful for cleanup work, like:

  • hiding a loading spinner
  • closing a connection
  • stopping a loader animation

.finally() does not care about success or failure. It simply runs at the end.

Real-world example: loading data

fetch("https://api.example.com/products")
.then(response => response.json())
.then(data => {
console.log("Products:", data);
})
.catch(error => {
console.log("Something went wrong:", error);
})
.finally(() => {
console.log("Request complete");
});

This is much cleaner than a deeply nested callback approach.

Why this matters in real systems

In real software, users do not judge your app only when things go right. They notice when things go wrong. Good promise-based error handling helps applications fail gracefully. Instead of blank screens or broken flows, you can show clear error messages, retry options, or fallback content.

6. Promise Chaining Concept

Promise chaining is one of the most important ideas in promises.

It allows us to perform multiple asynchronous steps in sequence, where each step depends on the result of the previous one.

For example:

  • fetch a user
  • then fetch that user’s posts
  • then fetch comments for the first post
  • then display everything

This is where promises become much better than nested callbacks.

Basic chaining example

Promise.resolve(5)
.then(value => {
return value * 2;
})
.then(newValue => {
return newValue + 10;
})
.then(finalValue => {
console.log(finalValue);
});

Output:

20

What is happening here

  • first promise gives 5
  • first .then() returns 10
  • second .then() receives 10, returns 20
  • third .then() receives 20

Each .then() returns a new promise. That is why chaining works. The next .then() waits for the previous one to complete.

Chaining async tasks

getUser()
.then(user => getOrders(user.id))
.then(orders => getOrderDetails(orders[0].id))
.then(details => {
console.log(details);
})
.catch(error => {
console.error("Error:", error);
});

This reads like a sequence of steps instead of nested branches.

Important rule: return values properly

A common beginner mistake is forgetting to return a promise or value inside .then().

Wrong:

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

Here getOrders(user.id) is called, but not returned. So the next .then() does not receive its result properly.

Correct:

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

Or shorter:

getUser()
.then(user => getOrders(user.id))
.then(orders => console.log(orders));

Returning properly is what keeps the chain connected.

Error propagation in chains

Another major benefit of chaining is that errors can travel down the chain until they are caught.

getUser()
.then(user => getOrders(user.id))
.then(orders => getOrderDetails(orders[0].id))
.then(details => console.log(details))
.catch(error => console.log("Caught error:", error));

If any step fails, the .catch() can handle it. This is much cleaner than manually checking errors at every nested level.

Why this matters in real systems

Real applications often involve workflows, not single steps. Logging in, loading dashboard data, validating a payment, and then sending a receipt are all chained actions. Promise chaining lets you express these workflows in a readable sequence, which makes the code easier to maintain and debug.

7. Comparing Promises with Callbacks

This comparison helps beginners see why promises feel cleaner.

Callback style

loginUser(username, password, function(user, error) {
if (error) {
console.log(error);
} else {
fetchProfile(user.id, function(profile, error) {
if (error) {
console.log(error);
} else {
fetchSettings(profile.id, function(settings, error) {
if (error) {
console.log(error);
} else {
console.log(settings);
}
});
}
});
}
});

This is hard to read because:

  • many nested layers
  • repeated error checks
  • unclear visual flow
  • difficult maintenance

Promise style

loginUser(username, password)
.then(user => fetchProfile(user.id))
.then(profile => fetchSettings(profile.id))
.then(settings => console.log(settings))
.catch(error => console.log(error));

This version is easier because:

  • it reads top to bottom
  • less nesting
  • error handling is centralized
  • steps are clearer

Promises do not eliminate asynchronous complexity completely, but they make it much more manageable.

Readability improvement

One of the biggest advantages of promises is readability. Humans understand sequences better than deeply nested blocks. When code looks closer to a logical story, it becomes easier to understand:

  • first do this
  • then do this
  • then do this
  • if anything fails, handle it

This style is easier for teams to work with and easier for beginners to debug.

8. A Beginner-Friendly Example from Real Life

Let us imagine you are building a shopping app.

When the user opens the page:

  1. fetch product data
  2. display products
  3. if request fails, show an error message
  4. hide loading spinner at the end

With promises:

console.log("Loading products...");

fetch("https://api.example.com/products")
.then(response => response.json())
.then(products => {
console.log("Products loaded:", products);
})
.catch(error => {
console.log("Could not load products:", error);
})
.finally(() => {
console.log("Stop loading spinner");
});

This example shows the full promise flow:

  • pending while fetch is happening
  • fulfilled when data arrives
  • rejected if something goes wrong
  • finally runs either way

This is why promises are so useful in modern web development.

9. Common Beginner Confusions

“Why can’t I just store the promise in a variable and use it like normal data?”

Because the promise is not the finished result. It is only the future result.

Wrong thinking:

let data = fetch("https://api.example.com/users");
console.log(data.name);

This will not work because data is a promise, not the actual user object.

Correct thinking:

fetch("https://api.example.com/users")
.then(response => response.json())
.then(data => {
console.log(data);
});

“Why does .then() come later?”

Because the value arrives later. .then() tells JavaScript what to do when the promise is eventually fulfilled.

“Can a promise finish more than once?”

No. Once settled, a promise stays settled.

“Do promises make code synchronous?”

No. The work is still asynchronous. Promises only provide a cleaner way to manage it.

10. Why Promises Matter in Real Systems

Promises are not just an interview topic. They are part of everyday development.

They matter because modern applications constantly deal with delayed work:

  • API requests
  • authentication
  • payment confirmation
  • chat updates
  • uploads and downloads
  • file reads
  • background tasks

Without a good way to manage async behavior, code quickly becomes hard to understand. Promises bring structure, readability, and reliable error handling.

They also form the foundation for async/await, which is one of the most common modern JavaScript patterns. If promises are unclear, async/await will also feel unclear. But if promises make sense, async/await becomes much easier.

In team environments, readable async code is extremely valuable. Developers need to quickly understand flows, find bugs, and safely update logic. Promise-based code is generally easier to maintain than deeply nested callback code.

Summary

Promises are JavaScript’s way of representing a future result. They solve the problem of managing asynchronous tasks in a cleaner and more readable way than callbacks. A promise starts in the pending state, then becomes either fulfilled when successful or rejected when something fails. We handle success with .then(), failure with .catch(), and optional cleanup with .finally().

The biggest power of promises comes from chaining, where multiple async steps can be written in a clean sequence. This makes code easier to read, easier to debug, and easier to maintain. Once you understand promises as “future values,” the topic becomes much more natural.

Key Takeaways

  • A promise represents a value that may be available in the future.
  • Promises solve the readability and maintainability problems caused by nested callbacks.
  • A promise has three states: pending, fulfilled, and rejected.
  • A promise starts as pending and settles only once.
  • .then() handles success.
  • .catch() handles failure.
  • .finally() runs after completion regardless of success or failure.
  • Promise chaining allows sequential async steps to be written in a cleaner way.
  • Returning values or promises inside .then() is important for proper chaining.
  • Modern JavaScript features like async/await are built on top of promises.

Glossary of Important Terms

Asynchronous
A task that does not finish immediately and completes later.

Promise
A JavaScript object representing a future success value or failure result.

Pending
The state where the promise is still waiting for completion.

Fulfilled
The state where the promise completed successfully.

Rejected
The state where the promise failed.

Resolve
The function used to mark a promise as successful.

Reject
The function used to mark a promise as failed.

.then()
A method used to handle a fulfilled promise.

.catch()
A method used to handle a rejected promise.

.finally()
A method that runs after the promise is settled, whether success or failure.

Chaining
Connecting multiple .then() calls so async steps happen in order.

Callback
A function passed into another function to be called later.

Callback Hell
Messy nested callback code that becomes hard to read and maintain.

Diagram Ideas

1. Promise Lifecycle Diagram

A visual flow like this:

Promise Created
|
v
Pending
/ \
v v
Fulfilled Rejected
| |
v v
.then() .catch()
\ /
v v
.finally()

2. Callback vs Promise Comparison

Callback style

Step 1
└── Step 2
└── Step 3
└── Step 4

Promise style

Step 1
|
v
Step 2
|
v
Step 3
|
v
Step 4

This comparison clearly shows why promises are easier to read.

Final Thought

Promises are really about one simple idea: some values take time to arrive. Once you accept that, promises stop feeling scary. They are just JavaScript’s structured way of saying, “the result is not ready yet, but I’ll let you know when it is.”

When you learn promises well, asynchronous JavaScript becomes much less stressful. And once this foundation is strong, moving to async/await becomes much smoother.

--

--