Understanding JavaScript Promises: A Comprehensive Guide to Create Your Own From Scratch
Understanding promises — from creation, chaining, and error handling to advanced features — empowers developers to write cleaner and more maintainable asynchronous code.
Join the DZone community and get the full member experience.
Join For FreeAsynchronous programming is an essential pillar of modern web development. Since the earliest days of Ajax, developers have grappled with different techniques for handling asynchronous tasks. JavaScript’s single-threaded nature means that long-running operations — like network requests, reading files, or performing complex calculations — must be done in a manner that does not block the main thread. Early solutions relied heavily on callbacks, leading to issues like “callback hell,” poor error handling, and tangled code logic.
Promises offer a cleaner, more structured approach to managing async operations. They address the shortcomings of raw callbacks by providing a uniform interface for asynchronous work, enabling easier composition, more readable code, and more reliable error handling. For intermediate web engineers who already know the basics of JavaScript, understanding promises in depth is critical to building robust, efficient, and maintainable applications.
In this article, we will:
- Explain what a promise is and how it fits into the JavaScript ecosystem.
- Discuss why promises were introduced and what problems they solve.
- Explore the lifecycle of a promise, including its three states.
- Provide a step-by-step example of implementing your own simplified promise class to deepen your understanding.
By the end of this article, you will have a solid grasp of how promises work and how to use them effectively in your projects.
What Is a Promise?
A promise is an object representing the eventual completion or failure of an asynchronous operation. Unlike callbacks — where functions are passed around and executed after a task completes — promises provide a clear separation between the asynchronous operation and the logic that depends on its result.
In other words, a promise acts as a placeholder for a future value. While the asynchronous operation (such as fetching data from an API) is in progress, you can attach handlers to the promise. Once the operation completes, the promise either:
- Fulfilled (Resolved): The promise successfully returns a value.
- Rejected: The promise fails and returns a reason (usually an error).
- Pending: Before completion, the promise remains in a pending state, not yet fulfilled or rejected.
The key advantage is that you write your logic as if the value will eventually be available. Promises enforce a consistent pattern: an asynchronous function returns a promise that can be chained and processed in a linear, top-down manner, dramatically improving code readability and maintainability.
Why Do We Need Promises?
Before the introduction of promises, asynchronous programming in JavaScript often relied on nesting callbacks:
getDataFromServer((response) => {
parseData(response, (parsedData) => {
saveData(parsedData, (saveResult) => {
console.log("Data saved:", saveResult);
}, (err) => {
console.error("Error saving data:", err);
});
}, (err) => {
console.error("Error parsing data:", err);
});
}, (err) => {
console.error("Error fetching data:", err);
});
This pattern easily devolves into what is commonly known as “callback hell” or the “pyramid of doom.” As the complexity grows, so does the difficulty of error handling, code readability, and maintainability.
Promises solve this by flattening the structure:
getDataFromServer()
.then(parseData)
.then(saveData)
.then((result) => {
console.log("Data saved:", result);
})
.catch((err) => {
console.error("Error:", err);
});
Notice how the .then()
and .catch()
methods line up vertically, making it clear what happens sequentially and where errors will be caught. This pattern reduces complexity and helps write code that is closer in appearance to synchronous logic, especially when combined with async/await
syntax (which builds on promises).
The Three States of a Promise
A promise can be in one of three states:
- Pending: The initial state. The async operation is still in progress, and the final value is not available yet.
- Fulfilled (resolved): The async operation completed successfully, and the promise now holds a value.
- Rejected: The async operation failed for some reason, and the promise holds an error or rejection reason.
A promise’s state changes only once: from pending
to fulfilled
or pending
to rejected
. Once settled (fulfilled or rejected), it cannot change state again.
Consider the lifecycle visually:
┌──────────────────┐ | Pending | └───────┬──────────┘ | v ┌──────────────────┐ | Fulfilled | └──────────────────┘ or ┌──────────────────┐ | Rejected | └──────────────────┘
Building Your Own Promise Implementation
To fully grasp how promises work, let’s walk through a simplified custom promise implementation. While you would rarely need to implement your own promise system in production (since the native Promise API is robust and well-optimized), building one for learning purposes is instructive.
Below is a simplified version of a promise-like implementation. It’s not production-ready, but it shows the concepts:
const PROMISE_STATUS = {
pending: "PENDING",
fulfilled: "FULFILLED",
rejected: "REJECTED",
};
class MyPromise {
constructor(executor) {
this._state = PROMISE_STATUS.pending;
this._value = undefined;
this._handlers = [];
try {
executor(this._resolve.bind(this), this._reject.bind(this));
} catch (err) {
this._reject(err);
}
}
_resolve(value) {
if (this._state === PROMISE_STATUS.pending) {
this._state = PROMISE_STATUS.fulfilled;
this._value = value;
this._runHandlers();
}
}
_reject(reason) {
if (this._state === PROMISE_STATUS.pending) {
this._state = PROMISE_STATUS.rejected;
this._value = reason;
this._runHandlers();
}
}
_runHandlers() {
if (this._state === PROMISE_STATUS.pending) return;
this._handlers.forEach((handler) => {
if (this._state === PROMISE_STATUS.fulfilled) {
if (handler.onFulfilled) {
try {
const result = handler.onFulfilled(this._value);
handler.promise._resolve(result);
} catch (err) {
handler.promise._reject(err);
}
} else {
handler.promise._resolve(this._value);
}
}
if (this._state === PROMISE_STATUS.rejected) {
if (handler.onRejected) {
try {
const result = handler.onRejected(this._value);
handler.promise._resolve(result);
} catch (err) {
handler.promise._reject(err);
}
} else {
handler.promise._reject(this._value);
}
}
});
this._handlers = [];
}
then(onFulfilled, onRejected) {
const newPromise = new MyPromise(() => {});
this._handlers.push({ onFulfilled, onRejected, promise: newPromise });
if (this._state !== PROMISE_STATUS.pending) {
this._runHandlers();
}
return newPromise;
}
catch(onRejected) {
return this.then(null, onRejected);
}
}
// Example usage:
const p = new MyPromise((resolve, reject) => {
setTimeout(() => resolve("Hello from MyPromise!"), 500);
});
p.then((value) => {
console.log(value); // "Hello from MyPromise!"
return "Chaining values";
})
.then((chainedValue) => {
console.log(chainedValue); // "Chaining values"
throw new Error("Oops!");
})
.catch((err) => {
console.error("Caught error:", err);
});
What’s happening here?
- Construction: When you create a
new MyPromise()
, you pass in an executor function that receives_resolve
and_reject
methods as arguments. - State and Value: The promise starts in the
PENDING
state. Onceresolve()
is called, it transitions toFULFILLED
. Oncereject()
is called, it transitions toREJECTED
. - Handlers Array: We keep a queue of handlers (the functions passed to
.then()
and.catch()
). Before the promise settles, these handlers are stored in an array. Once the promise settles, the stored handlers run, and the results or errors propagate to chained promises. - Chaining: When you call
.then()
, it creates a newMyPromise
and returns it. Whatever value you return inside the.then()
callback becomes the result of that new promise, allowing chaining. If you throw an error, it’s caught and passed down the chain to.catch()
. - Error Handling: Similar to native promises, errors in
.then()
handlers immediately reject the next promise in the chain. By having a.catch()
at the end, you ensure all errors are handled.
While this code is simplified, it reflects the essential mechanics of promises: state management, handler queues, and chainable operations.
Best Practices for Using Promises
- Always return promises: When writing functions that involve async work, return a promise. This makes the function’s behavior predictable and composable.
- Use .catch() at the end of chains: To ensure no errors go unhandled, terminate long promise chains with a
.catch()
. - Don’t mix callbacks and promises needlessly: Promises are designed to replace messy callback structures, not supplement them. If you have a callback-based API, consider wrapping it in a promise or use built-in promisification functions.
- Leverage utility methods: If you’re waiting on multiple asynchronous operations, use
Promise.all()
,Promise.race()
,Promise.allSettled()
, orPromise.any()
depending on your use case. - Migrate to async/await where possible: Async/await syntax provides a cleaner, more synchronous look. It’s generally easier to read and less prone to logical errors, but it still relies on promises under the hood.
Conclusion
Promises revolutionized how JavaScript developers handle asynchronous tasks. By offering a structured, composable, and more intuitive approach than callbacks, promises laid the groundwork for even more improvements, like async/await. For intermediate-level engineers, mastering promises is essential. It ensures you can write cleaner, more maintainable code and gives you the flexibility to handle complex asynchronous workflows with confidence.
We covered what promises are, why they are needed, how they work, and how to use them effectively. We also explored advanced techniques like Promise.all()
and wrote a simple promise implementation from scratch to illustrate the internal workings. With this knowledge, you’re well-equipped to tackle asynchronous challenges in your projects, building web applications that are more robust, maintainable, and ready for the real world.
Opinions expressed by DZone contributors are their own.
Comments