Asynchronous JavaScript: Promises & async/await
In early JavaScript, handling asynchronous operations (like requesting data from an API, querying a database, or reading a file) required nesting callback functions inside callback functions.
This led to the infamous "Callback Hell" (also called the Pyramid of Doom):
// The Pre-ES6 Callback Hell:getUser(userId, (user) => { getOrders(user.id, (orders) => { getOrderDetails(orders[0].id, (details) => { calculateTotal(details, (total) => { // Deeply indented, brittle, error handling nightmare! }); }); });});To solve this, modern JavaScript introduced Promises in ES6 and async/await in ES2017, transforming asynchronous programming into clean, sequential, and readable code.
1. What is a Promise?
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value.
The 3 States of a Promise
┌───────────────┐
│ <pending> │
└───────┬───────┘
│
┌───────────────┴───────────────┐
▼ ▼
┌───────────────┐ ┌───────────────┐
│ <fulfilled> │ │ <rejected> │
│ (Success Val) │ │ (Error Reason)│
└───────────────┘ └───────────────┘
<pending>: The initial state. The operation is still in flight (e.g., waiting for an API response).<fulfilled>: The operation succeeded! The promise now holds a resolved value.<rejected>: The operation failed. The promise now holds a rejection error reason.
[!IMPORTANT] The Immutability Rule of Promises: Once a promise settles into either
<fulfilled>or<rejected>, its state can never change again. If a function attempts to callresolve()and then later callsreject(), the second call is completely ignored.
2. Interactive Promise & Async/Await Studio
Experiment with state transitions, simulate network successes and 404 failures, inspect async/await equivalence, and test parallel combinators in real-time.
Promise & Async/Await Studio
Async ArchitectureInspect how Promises transition through immutable states and how async/await transforms asynchronous control flow.
.then(value => ...) handlers..catch(error => ...) handlers.Click a trigger to simulate asynchronous network resolution after a 1.2s delay.
const fetchUser = new Promise((resolve, reject) => {
// Simulating async network call:
setTimeout(() => {
if (networkSuccess) {
resolve({ id: 42, username: "priya_dev" });
} else {
reject(new Error("404 User Not Found"));
}
}, 1200);
});
fetchUser
.then(data => console.log("User:", data))
.catch(err => console.error("Failed:", err));fulfilled or rejected, it is permanently locked. Subsequent calls to resolve() or reject() are silently ignored!3. Promise Chaining & Error Propagation
Unlike callbacks, promises allow you to chain operations sequentially:
fetchUser(42) .then(user => fetchUserPosts(user.id)) .then(posts => posts.filter(p => p.published)) .then(publishedPosts => console.log("Published:", publishedPosts)) .catch(error => { // Catches ANY error that occurred in ANY step above! console.error("Pipeline failed:", error.message); }) .finally(() => { // Runs regardless of success or failure (e.g. hide loading spinner) stopLoadingSpinner(); });The Power of .catch()
In a promise chain, you don't need error handling at every individual step. Errors bubble down the chain automatically until they encounter the first .catch() block.
4. async/await: Modern Synchronous-Style Syntax
Introduced in ES2017, the async and await keywords make asynchronous code read almost identically to synchronous code:
async function loadDashboard(userId) { try { const user = await fetchUser(userId); const posts = await fetchUserPosts(user.id); const published = posts.filter(p => p.published); return published; } catch (error) { console.error("Dashboard error:", error); throw error; } finally { stopLoadingSpinner(); }}Two Golden Rules of async/await:
- The
asynckeyword: Prependingasyncto any function guarantees that it always returns a Promise. If you return a primitive string or number, JavaScript wraps it inPromise.resolve(). - The
awaitkeyword: Can only be used insideasyncfunctions (or at the top level of modern ES modules). It temporarily pauses function execution until the promise settles, then unwraps the fulfilled value.
5. Parallel Execution: Promise Combinators
When you have multiple independent asynchronous operations, running them sequentially with consecutive await statements slows down your application. JavaScript provides 4 combinators to run tasks in parallel:
| Combinator | Behavior | When to Use |
|---|---|---|
Promise.all([p1, p2]) | Fulfills when ALL fulfill. Rejects immediately if any single promise rejects (all-or-nothing). | Loading critical page data that all depends on each other. |
Promise.allSettled([p1, p2]) | Never rejects. Waits for all promises to finish and returns an array of { status, value/reason }. | Bulk operations where partial successes are acceptable. |
Promise.race([p1, p2]) | Settles as soon as the first promise settles (whether fulfilled or rejected). | Implementing request timeouts (e.g., fetch vs. 5s timer). |
Promise.any([p1, p2]) | Fulfills as soon as the first promise fulfills (ignores rejections until all fail). | Querying multiple fallback CDNs or mirrors for a file. |
// Running 3 requests in parallel:const [profile, posts, settings] = await Promise.all([ fetchProfile(), fetchPosts(), fetchSettings()]);6. Flashcards & Core Concepts
What are the 3 states of a JavaScript Promise?
What is the difference between Promise.all() and Promise.allSettled()?