JavaScript · Lesson 11 of 20 · 4 min
Asynchronous JavaScript: Callbacks & Promises
This is how you prove you can handle real-world data fetching and avoid the race conditions and unhandled errors that plague junior code.
The Single-Thread Problem
JavaScript executes on a single thread. This means it can only do one thing at a time. If you start a long-running task, like a network request or a complex calculation, the entire browser UI will freeze until it's done. No clicks, no scrolling, nothing.
Asynchronous operations are the solution. You kick off a task (e.g., fetch('/api/data')) and provide a way to handle the result when it's ready. In the meantime, the main thread is free to continue executing other code, keeping the UI responsive. The mechanism that juggles this is the Event Loop, which processes a queue of tasks once the main call stack is empty.
Callbacks: The Original Pattern
A callback is just a function you pass to another function, expecting it to be called later. This is the oldest async pattern in JavaScript. You see it everywhere, from event listeners (button.addEventListener('click', handleClick)) to timers (setTimeout(doSomething, 1000)).
For a single async operation, callbacks are fine. The problem arises when you need to perform several async operations in sequence, where each step depends on the result of the previous one. This leads to deeply nested functions, a pattern notoriously known as "Callback Hell" or the "Pyramid of Doom." It's hard to read, harder to reason about, and a nightmare for error handling.
// The "Pyramid of Doom"
getUser(1, (userError, user) => {
if (userError) {
console.error(userError);
return;
}
console.log("User:", user);
getUserPosts(user.id, (postsError, posts) => {
if (postsError) {
console.error(postsError);
return;
}
console.log("Posts:", posts);
getPostComments(posts[0].id, (commentsError, comments) => {
if (commentsError) {
console.error(commentsError);
return;
}
console.log("Comments:", comments);
// And so on...
});
});
});
Each nested function creates a new scope for error handling and logic, leading to repetitive if (error) checks and a structure that drifts to the right.
Promises: A Structured Approach
A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation. Think of it as a placeholder for a future value. It gives us a cleaner, more composable way to manage async code.
A promise exists in one of three states:
- Pending: The initial state; the operation has not completed yet.
- Fulfilled: The operation completed successfully, and the promise has a resulting value.
- Rejected: The operation failed, and the promise has a reason (an error).
Once a promise is settled (fulfilled or rejected), its state and value are immutable. You consume a promise by attaching handlers using .then() for fulfillment, .catch() for rejection, and .finally() for any cleanup.
From Callback Hell to Promise Chains
Promises flatten the pyramid of doom into a linear, readable chain. Each .then() in the chain receives the result of the previous one and can either return a value or another promise.
Here is the same logic from before, refactored to use promises. Notice the flat structure and the single, centralized error handler.
getUserP(1)
.then(user => {
console.log("User:", user);
return getUserPostsP(user.id); // Return the next promise
})
.then(posts => {
console.log("Posts:", posts);
if (posts.length === 0) {
// If there are no posts, we can stop the chain
// by returning a promise that resolves to an empty array.
return Promise.resolve([]);
}
return getPostCommentsP(posts[0].id);
})
.then(comments => {
console.log("Comments:", comments);
})
.catch(error => {
// A single catch block handles errors from any point in the chain.
console.error("An error occurred in the promise chain:", error);
});
The trap: Forgetting to
returna promise from a.then()block breaks the chain. The next.then()will execute immediately withundefinedas its input, not waiting for your async operation to finish. This is one of the most common bugs when learning promises.
Handling Multiple Promises in Parallel
Sometimes you need to run multiple independent async operations and wait for them all to finish. Manually chaining them would be inefficient, as they would run sequentially. Promise combinators solve this.
Promise.all(promises) takes an array of promises and returns a single promise.
- It fulfills when all input promises have fulfilled, returning an array of their results.
- It rejects as soon as any one of the input promises rejects (it's "fail-fast").
Use Promise.all when all operations must succeed for the overall task to be successful.
Promise.allSettled(promises) also takes an array of promises.
- It fulfills when all input promises have settled (either fulfilled or rejected).
- It never rejects. The result is an array of objects, each describing the outcome (
status: 'fulfilled', value: ...orstatus: 'rejected', reason: ...) of a promise.
Use Promise.allSettled when you need to know the outcome of every operation, regardless of individual failures. For example, fetching data from multiple independent widgets on a dashboard.
Try it
Implement a function fetchWithRetry(url, retries) that uses the fetch API. It should attempt to fetch the URL. If the request fails (e.g., network error), it should retry up to retries times before finally rejecting the promise. Use promise chaining and a recursive helper function inside.
Next: In ES6+ Features (Part 1), we'll cover async/await, the modern syntax that makes working with promises even more intuitive.
Lock it in — apply this lesson under interview conditions.