Back to Explore
GuideVibeFix editorialUpdated Nov 19, 2026

Stop async code from failing quietly: a practical guide to Promises and async/await

A Promise is not magic: it is a way of saying what happens when a result comes back. This guide follows MDN's Using promises guide and the Promise reference: three states, the return rule for then, flat chains, async/await, the four concurrency tools, microtask timing, and a five-category failure breakdown.

Real photo: hands typing on a laptop keyboard, a dark code editor on the screen, a cup of coffee on the desk

First, the boundaries of this guide. The site already has a guide on async collaboration workflows, about how people and AI assistants split up long-running tasks — that one is about collaboration, while this one is about code: in JavaScript, when you wait for a result to come back, how many ways are there to write it, and where does each way break? There is also a guide on URL query parameters, about taking addresses apart; this guide is not about addresses, only about time: what runs first, what runs next, and which things can run together. The "Misty Island Shop" used below is a fictional practice project: a small web tool that takes orders for a street-side shop — it checks stock, then works out the price, then submits the order. Every operation, code sample, and number built around it was invented to explain the technique, not a real record. All syntax, methods, and behavior of Promises come from MDN's "Using promises" guide and the Promise reference page; see each article's meta information and evidence record for sources. MDN's own examples, such as the doSomething chain and the ingredients list, are the documentation's examples, not real user data.

Step 1: Why the callback pyramid hurts

On the web, many things do not produce a result right away: fetching a menu from a server waits on the network, reading a local file waits on the disk, a timer waits for time to pass. The earliest way to write this was callbacks: you write "what to do when it is done" as a function and pass it in as an argument. That is fine for one thing. But once the job becomes "check the stock first, then work out the price if there is enough, then submit the order," callbacks have to nest inside each other. MDN gives a vivid example: doSomething wrapping doSomethingElse, wrapping doThirdThing, with the failureCallback repeated at every level. The code narrows to the right like a pyramid, and it is harder to change than to read: if you want to add a check in the middle, or collect error handling in one place, you have to touch three nested levels at once, and missing one lets an error slip away quietly.

Step 2: A Promise has only three states — learn them and you will not get lost

A Promise has only three states from the moment it is born. The first is pending: the job is not finished, and success or failure is still unknown. The second is fulfilled: the job succeeded, carrying a success value. The third is rejected: the job failed, carrying a failure reason. MDN's Promise reference page states this strictly: a pending Promise can only end up fulfilled or rejected, one of the two; once it settles, its state never changes again. A fulfilled Promise will never become rejected, and a rejected one will never become fulfilled. This "once settled, never changes" guarantee is the foundation for everything that follows.

How does the state change? There are only two routes. When you create a Promise, you pass in an executor function, which runs synchronously right away and receives two functions as arguments: resolve and reject. Call resolve with a value inside the executor and the Promise fulfills with that value; call reject with a reason and it rejects with that reason. The executor itself runs synchronously — a point the section on microtask timing will come back to verify. Many beginners assume the code inside new Promise is asynchronous. It is not: by the time new Promise returns, the executor has already run; only the timing of the then callbacks is asynchronous.

Step 3: then returns a new Promise — forget return and the chain breaks

The most important sentence about Promises is one MDN writes at the start of the guide: the then method returns a new Promise, different from the original. This new Promise represents not only the completion of the original job, but also the completion of the success or failure callback you passed in. If the callback returns another Promise, the new Promise waits for it to settle first, then passes its fulfillment value to the next callback. That is how a chain links up, one section after another: doSomething().then(check stock).then(work out the price).then(submit the order).catch(handle all failures). Each section's input is the previous section's output, and the order on the page is the order of execution — exactly what the callback pyramid cannot do.

This rule brings an iron law: whenever a then callback meets a Promise, return it. MDN makes the consequence concrete with an ingredients-list example: doSomething first returns a URL, the callback calls fetch to get the data but forgets to write return, so the next then receives undefined — worse, the next section runs before fetch has finished, and the ingredients list always prints as an empty array. Without the return, the Promise becomes a "floating" promise: it keeps running in the background, but the chain no longer tracks it, and the chain never learns whether it succeeded or failed. Worse still is the race: if a later step reads a result from an earlier one while the earlier request is still in flight, it reads half-written data — sometimes right, sometimes wrong, and hard to reproduce in testing.

The fix is a single sentence: whenever you meet a Promise, return it and let the next then handle it. MDN also offers a more thorough suggestion: flatten nested chains. The ingredients example originally nested fetch().then().then() inside an outer then; flattened, it becomes one section after another: first get the URL, then fetch, then parse the JSON, then put it in the list. Every step is one section, and error handling needs only one catch. Flattening is not about looks; it means there is only one exit for errors, and when debugging you can walk down the chain with every step's input and output visible.

Step 4: Error handling has one exit — but nesting opens a side door

The most reassuring thing about a Promise chain is that errors travel down the chain looking for a catch. MDN draws a comparison with synchronous code: in synchronous code, a try block wraps three steps, and an error in any step falls into the same catch; a Promise chain works the same way — an error thrown in any section, or a rejected Promise returned by one, travels downward until a catch receives it. So in normal cases you do not need failure handling in every section; one catch at the end of the chain covers the whole chain. MDN's own words are that you should almost never need try/catch without using async/await — the catch at the end of the chain is your try/catch.

But this "one exit" has an exception: nesting. MDN explains that nesting is a control structure for limiting the scope of a catch statement: an inner catch only handles failures in its own scope and below, not errors higher up the chain outside the nested scope. The example in the docs puts doSomethingOptional and doSomethingExtraNice inside a nested block after doSomethingCritical; the inner catch quietly swallows failures in the optional steps and the chain continues to the more critical moreCriticalStuff; but if the first step, doSomethingCritical, fails, the inner catch does not receive it — only the outer catch at the end does. The technique itself is sound: it makes "the optional steps can fail and we still continue" possible. The cost is that the chain now has two exits. MDN's advice is blunt: if you do not need error handling this precise, do not nest then handlers; use a flat chain and put the error handling at the end. Nesting is not forbidden — it just means that with every nesting, you have to think once more about which steps a given catch actually covers.

Step 5: async/await is the same thing written differently

async/await is not a replacement for Promises; it is Promises written another way. MDN's own words are that async/await builds on promises. Rewriting the ingredients example with async/await makes the code look exactly like synchronous code, except for a few await keywords: first await doSomething to get the URL, then await fetch to get the response, then await res.json() to get the data, and finally put it in the list. It reads top to bottom, and changing it is easy too: to add a check in the middle, insert a line between two lines without rearranging brackets.

But "looks synchronous" does not mean "is synchronous." MDN flags two points. First, await only pauses the parts of its own async function that depend on the awaited value; the whole program does not stop, and other async jobs keep running. Second, an async function always returns a Promise: return an ordinary value inside it and the caller gets a Promise fulfilled with that value; throw inside it and the caller gets a rejected Promise. So async functions can still be chained, and awaiting an async function is the same thing as calling then on a Promise.

Error handling in async/await goes back to the synchronous shape: try/catch. MDN translates the chained example into async/await sentence by sentence: await the three steps in turn inside try, and receive failures in catch. When you want a failed optional step not to stop the key steps, nest another try/catch inside, wrapping only the two optional steps, while the outer catch only handles the key steps. This structure maps one to one onto the nested-then example from the previous section; the difference is only the writing: an inner try/catch is much easier to read than an inner then/catch, because the code does not indent to the right. Which style to choose is a team habit; but remember that a try/catch in async/await only catches rejections of Promises that were awaited. A Promise that was never awaited and rejects is not caught — the error becomes an unhandled rejection and slips away to the global scope.

Step 6: A forgotten await is the quietest failure

A forgotten return in a Promise chain breaks the chain; a forgotten await in async/await hands you a Promise to use as a value. MDN mentions this trap in a single sentence when introducing async/await: it is easy to forget the await keyword, and the only fix is a type mismatch — for example, trying to use a promise as a value. The fictional Misty Island Shop example can make the trap concrete. Suppose the order flow has three steps: checking stock returns a number, working out the price returns a number, and submitting the order returns an order number. If you write const stock = checkStock() and forget await, stock is a Promise; comparing it with 0 always yields false, so the program assumes there is always enough stock and walks straight to submitting the order. By the time the server reports insufficient stock, the order has already been submitted. There is no trick to the fix, only a habit: whenever you call a function that returns a Promise, first ask, "Do I need to wait for its result?" If yes, write await; if no, think through who will receive this Promise's failure — do not let it float. A team can agree on a rule: in an async function, calling an async function without await must carry a comment explaining why it is not awaited; otherwise it counts as a forgotten await.

Step 7: Four concurrency tools — first work out "who are we waiting for," then choose

Doing one thing and then the next is sequential; starting several things at the same time and waiting for their results together is concurrent. MDN lists four concurrency tools, all static methods on Promise, all taking an iterable and returning a new Promise. They differ in only one thing: the condition they wait for. Promise.all is "all of them": it fulfills when all fulfill, and rejects as soon as any one rejects. Promise.allSettled is "all of them must have a result": whether fulfilled or rejected, it fulfills once all have settled, and each item in the result states its status and value or reason. Promise.any is "any one will do": it fulfills when any one fulfills, and rejects only when all reject, carrying an AggregateError that holds all the rejection reasons. Promise.race is "whoever settles first wins": the first Promise to settle decides the outcome — fulfillment if it fulfills, rejection if it rejects.

The cost of choosing the wrong tool differs each time. MDN highlights one behavior of Promise.all in particular: when it rejects, the other jobs do not stop — they keep running in the background, but their results can no longer be reached. That can produce unexpected state: suppose the first of three jobs fails and all rejects at once, but the second job then succeeds and writes a record to the database, while your program believes the whole batch never ran. When "partial failure still needs a result for every item," use allSettled; when "any of three mirror sources will do, take whichever answers first," any fits better than race, because race treats the first rejection as the result while any waits for a success; only when you explicitly want "the first result, success or failure, to act as a timeout signal" is race the right choice. Before choosing a tool, write the problem as one sentence: "What condition counts as done?" The answer maps directly onto one of the four tools.

Step 8: Sequential or concurrent — first ask "does the next step need the previous step's result?"

After presenting the concurrency tools, MDN adds a sentence that is easy to overlook: before composing promises sequentially, consider whether it is really necessary — it is always better to run promises concurrently so that they do not unnecessarily block each other, unless one promise's execution depends on another's result. The test is a single question: does the next step need the previous step's result? The stock-check result decides whether to work out the price — that is a dependency, and it must be sequential; fetching the menu and fetching the user profile do not depend on each other, so they can run concurrently with Promise.all. Writing independent jobs sequentially makes the page wait extra network rounds for nothing; writing dependent jobs concurrently hands the later step data that has not finished computing. In the fictional shop example, the order page needs the menu, the user profile, and coupons at the same time, and the three do not depend on each other — with concurrent code the wait is roughly the slowest one; with sequential code it is the sum of all three. The difference is not a few milliseconds; on a slow network it can be seconds.

Step 9: Only write new Promise by hand when wrapping an old interface

MDN's own words are that creating a Promise from scratch should be needed only to wrap old APIs. In an ideal world, all asynchronous functions would already return promises; in reality, some old interfaces still expect callbacks, setTimeout being the most obvious example. The way to wrap one is to write the thinnest possible shell: const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), and then only ever call wait, never setTimeout directly again. Wrap at the lowest possible level, wrap once, and use it everywhere. If the old interface cannot fail, reject can be left out, as in wait; if it can fail, call reject in the failure callback so the failure enters the Promise world — otherwise the error can never reach a catch.

Step 10: Microtask timing — remember the numbers 1, 2, 3, 4

When do Promise callbacks run? MDN gives three hard guarantees. First, callbacks added with then will never be invoked before the completion of the current run of the JavaScript event loop. Second, they will be invoked even if they were added after the success or failure of the asynchronous operation the promise represents. Third, multiple callbacks may be added by calling then several times, and they will be invoked one after another, in the order in which they were inserted. Taken together, that means Promise callbacks are always asynchronous, always in order, and never lost.

The docs contain a set of numbers worth memorizing: Promise.resolve().then(() => console.log(2)), followed by console.log(1), always prints 1, then 2 — because the then callback is placed on the microtask queue and only runs after the current synchronous code has finished and the execution stack is empty. A fuller example is: wait(0).then(() => console.log(4)), then two thens printing 2 and 3, then console.log(1); the output is 1, 2, 3, 4. Microtasks run before timer tasks, so with the same zero-millisecond wait, the Promise callback runs before the setTimeout callback. There is also an example showing that the executor runs synchronously: inside new Promise it prints "Promise callback" first, then "Promise (pending)", then "Promise callback (.then)", and only later, inside setTimeout, "Promise (fulfilled)". That output demonstrates three things at once — the executor runs synchronously, then callbacks run as microtasks, and timers run last — and it is worth running by hand in the console.

Step 11: A rejection nobody receives bubbles up to the global scope

If a Promise rejects and no handler receives it, the error does not disappear; it bubbles to the top of the call stack, and the host has to surface it. In the browser, two global events are sent: unhandledrejection, when a promise is rejected but there is no rejection handler available; and rejectionhandled, when a handler is attached to a rejected promise that has already caused an unhandledrejection event. Both events carry a promise property naming the Promise and a reason property giving the reason for rejection. In Node.js the approach differs slightly: you listen for the process unhandledRejection event — note the different capitalization from the browser event name. MDN adds a warning: if in Node.js you add that listener but write no handling code inside it, rejected promises will simply be dropped on the floor and silently ignored, so the listener should examine each rejected promise and make sure it was not caused by a real code bug.

Step 12: Five failure scenes — check yourself against the chart

Bar chart of 96 async incidents in one quarter in the fictional Misty Island Shop project, by cause

The chart above shows a fictional quarter for the Misty Island Shop project: 96 async-related incidents in total. Forgotten return breaking the chain: 28, or 29.2%, the largest group; forgotten await, using a Promise as a value: 24, or 25.0%; choosing sequential when concurrent was right, or the reverse: 16, or 16.7%; catch placed in the wrong spot, so the failure that should have been caught was not: 15, or 15.6%; unhandled rejections bubbling to the global scope: 13, or 13.5%. 28 + 24 + 16 + 15 + 13 = 96, and the books balance. These numbers are invented examples, meant to show at a glance that the first two groups together are more than half — and that they are the same mistake in two different spellings: a missing return on the chain, or a missing await in front of a call.

Checklist: after writing async code, tick each item

First, the chain is flat, with no nesting for no reason; nesting appears only when the scope of a catch needs limiting. Second, every place a then callback returns a Promise carries a return, with no floating Promises. Third, every async call inside an async function either carries await or carries a comment explaining why it is not awaited. Fourth, the concurrency tool is the right one: all when all must succeed, allSettled when every item needs a result, any when any single success will do, race when the first settlement decides. Fifth, sequential and concurrent are told apart: if the next step does not need the previous step's result, run concurrently; if it does, run sequentially. Sixth, every failure has an exit: a catch at the end of the chain, a try/catch inside async functions. Seventh, new Promise is only written by hand when wrapping an old callback interface such as setTimeout. Eighth, then callbacks run after synchronous code and before timers. Ninth, cancellation is sought in an underlying mechanism such as AbortController. If any item cannot be answered, go back to its section and read it again — that is worth more than memorizing ten more APIs.

Views 2Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles

Real photo: a woman in an office sticking colorful sticky notes in rows on a white wall, holding a pink note in her hand
Guide
Stop shimming with margins: Flexbox one-dimensional layout, explained plainly

Flexbox lays things out in one direction at a time, and when it is done right, the nav bar, the card wall, and the cart rows all behave. This guide follows MDN's Basic concepts of flexbox, Aligning items in a flex container, and Controlling ratios of flex items along the main axis: the two axes, containers and items, direction and wrapping, free space, the three flex properties, alignment on both axes, and gaps and auto margins.

Developer WorkflowFrontend EngineeringAI Coding
Real photo: top-down view of hands sorting handwritten index cards on a dark desk, with clipboards holding tables beside them
Guide
Put the data in a labeled box first: objects and JSON, explained plainly

One order is one object: table, dishes, total, paid — all filed by label. This guide follows MDN's Working with objects, JSON, and Object references: object literals, dot vs bracket notation, adding and deleting properties, for...in with hasOwn, methods and this, getters and setters, references vs copies, Object.assign and friends, null-prototype objects, JSON's strict rules, and stringify and parse with their number-precision trap.

Developer WorkflowFrontend EngineeringAI Coding
Real photo: hands typing on a MacBook Pro showing JavaScript code that changes HTML content, with a white mouse, papers, and binders on a white desk
Guide
Functions without the confusion: JavaScript functions, parameters, and arrow functions, explained plainly

You already call functions every day; this guide names what you have been doing. Following MDN's Functions, Arrow function expressions, and Rest parameters: declarations versus expressions, parameters and arguments, default values, rest parameters, spread syntax, return values, arrow function shorthand, the this trap, callbacks, and scope.

Tool TipsFrontend EngineeringAI Coding