1. Home
  2. Blog
  3. Software Development

Software Development

JavaScript Promises Explained: then, catch, Promise.all and Common Mistakes

Promises are how JavaScript handles work that finishes later, and async/await is built on top of them. Learn how they really behave, with real output from each example, and avoid the mistakes that swallow your errors.

10 min read
JavaScript promises explained: then, catch, Promise.all and common mistakes

Key takeaways

  • A promise is an object representing a result that will be available later.
  • It is pending until it is either fulfilled or rejected, and once settled it never changes.
  • Each then returns a new promise, which is what makes chaining possible.
  • Use Promise.all when every result is required, and Promise.allSettled when you want every outcome.

Network requests, file reads and timers all finish later, but JavaScript cannot simply stop and wait, or the page would freeze. JavaScript promises give you a tidy way to say “when this finishes, do that, and if it fails, do this instead.”

Even if you mostly write async and await, you are using promises underneath, so understanding them makes debugging far easier. We ran these examples on Node.js 24, and the output shown comes from that run. They behave the same way in modern browsers.

What is a promise?

A promise is a placeholder for a future value. Think of the buzzer a restaurant hands you when you order. You do not have your food yet, but you hold something that will tell you when it is ready, or that there is a problem, and meanwhile you are free to do other things.

In code, an asynchronous function returns a promise immediately, and you attach what should happen next:

fetch("/api/user")
  .then((response) => response.json())
  .then((user) => console.log(user.name))
  .catch((error) => console.log("Failed:", error.message));

The three promise states

State Meaning What runs
Pending The work has not finished Nothing yet
Fulfilled It finished with a value then handlers
Rejected It failed with a reason catch handlers

A promise that is fulfilled or rejected is called settled. A promise can settle only once. After that, its state and value are fixed, and later calls to resolve or reject are ignored.

Create a promise

You usually consume promises from APIs like fetch, but creating one shows how they work. The constructor receives two functions, resolve and reject:

function fetchUser(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (id > 0) {
        resolve({ id, name: "Asha" });
      } else {
        reject(new Error("Invalid id"));
      }
    }, 100);
  });
}

console.log(fetchUser(1));

// Promise { <pending> }

Logging the promise right away shows it is still pending, because the timer has not fired. The value can only be reached through a handler or await. Always reject with an Error object rather than a string, since an Error carries a stack trace that helps with debugging.

then, catch and finally

These three methods attach handlers to a promise:

fetchUser(1).then((user) => console.log(user.name));
// Asha

fetchUser(-1)
  .then((user) => console.log("never runs", user))
  .catch((error) => console.log("caught:", error.message))
  .finally(() => console.log("finally"));

// caught: Invalid id
// finally

then runs on success, catch runs on failure and finally runs either way. That makes finally the right place for cleanup, such as hiding a loading spinner. It receives no arguments, because it should not care about the outcome.

Chaining promises

The key idea is that then always returns a new promise. Whatever your handler returns becomes that new promise’s value:

Promise.resolve(2)
  .then((n) => n * 10)
  .then((n) => n + 1)
  .then((n) => console.log("chain:", n));

// chain: 21

If a handler returns another promise, the chain waits for it to settle before moving on. This is what turns nested callbacks into a flat sequence of steps:

getUser(id)
  .then((user) => getOrders(user.id))
  .then((orders) => getInvoice(orders[0].id))
  .then((invoice) => console.log(invoice.total))
  .catch(handleError);

How errors travel through a chain

A rejected promise skips every then until it reaches a catch. Throwing inside a handler counts as a rejection too. And a catch that returns normally gets the chain back on track:

Promise.resolve("start")
  .then(() => {
    throw new Error("step 2 failed");
  })
  .then(() => console.log("skipped"))
  .catch((error) => {
    console.log("caught:", error.message);
    return "recovered";
  })
  .then((value) => console.log("continues:", value));

// caught: step 2 failed
// continues: recovered

Think of this as the asynchronous version of try and catch. One catch at the end usually covers the whole chain. If you only want to log an error and still fail, throw it again from inside the catch.

Tip: fetch rejects only for network failures. A 404 or 500 response still fulfills, so check response.ok yourself. Our HTTP status codes cheat sheet explains what each code means.

Promise.all, allSettled, race and any

These static methods coordinate several promises at once. All of them take an array and return one promise.

Method Fulfills when Rejects when Use it for
Promise.all All fulfill Any one rejects All results are required
Promise.allSettled All settle Never You want every outcome
Promise.race The first to settle fulfills The first to settle rejects Timeouts
Promise.any The first fulfills All reject The first successful source

To test them, we used two small helpers, one that succeeds after a delay and one that fails after a delay:

const wait = (ms, value) =>
  new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fail = (ms, message) =>
  new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));

Promise.all

await Promise.all([wait(300, "a"), wait(100, "b"), wait(200, "c")]);

// [ 'a', 'b', 'c' ]   took about 300 ms

Two details to notice. Results keep the input order, even though b finished first. And the total time was about 300 ms, the time of the slowest task and not the 600 ms sum, because all three were already running at once. If any one of them rejects, the whole thing rejects straight away:

await Promise.all([wait(100, "a"), fail(50, "b failed")]);

// rejected: b failed

Promise.allSettled

This waits for everything and reports each result, so one failure does not lose the rest. It suits a dashboard where each widget loads independently:

const results = await Promise.allSettled([wait(50, "a"), fail(50, "b failed")]);
results.map((r) => r.status);

// [ 'fulfilled', 'rejected' ]

Promise.race and Promise.any

await Promise.race([wait(300, "slow"), wait(100, "fast")]);   // fast
await Promise.any([fail(50, "x"), wait(100, "ok")]);          // ok

The difference is that race takes the first to settle, even if it failed, while any ignores failures as long as something succeeds. A classic use of race is adding a timeout to a slow request, though the slower task keeps running in the background unless you cancel it.

Promises and async/await

async and await are a more readable way to work with the same promises. An async function always returns a promise, and await pauses that function until a promise settles:

async function showInvoice(id) {
  try {
    const user = await getUser(id);
    const orders = await getOrders(user.id);
    console.log(orders.length);
  } catch (error) {
    console.log("Failed:", error.message);
  }
}

Rejections become thrown errors, so ordinary try and catch works. You still need Promise.all for parallel work, because awaiting one call after another runs them in sequence. Our JavaScript async/await guide goes deeper on this.

Promises and the event loop

Promise handlers are never called immediately, even when the promise has already settled. They run after the current code finishes, and before any timers. Here is the proof:

setTimeout(() => console.log("timeout"), 0);
Promise.resolve().then(() => console.log("microtask"));
console.log("sync");

// sync
// microtask
// timeout

Synchronous code runs first. Next comes the microtask queue, which holds promise handlers. Only then does the event loop pick up the next task, such as a timer. This is a popular interview question, and it explains why a setTimeout of zero is not really immediate.

Promises vs callbacks

Concern Callbacks Promises
Sequencing Nested, deeper at each step A flat chain
Errors Checked at every level One catch can cover the chain
Parallel work Manual counters Promise.all
Called twice by mistake? Possible Cannot settle twice

Common mistakes

  • Forgetting to return inside then. Without a return, the next step receives undefined and does not wait for your inner promise.
  • No catch at all. This causes an unhandled rejection, and in Node.js that stops the process by default.
  • Nesting instead of chaining. Putting then inside then recreates callback hell. Return the promise and continue the chain.
  • Wrapping a promise in new Promise. If a function already returns a promise, just use it.
  • Using forEach with async callbacks. It does not wait. Use for...of or Promise.all with map, as shown in our guide to JavaScript array methods.
  • Thinking a promise can be cancelled. It cannot on its own. For requests, use AbortController.

Final thoughts

Promises come down to a few rules: a promise settles once, then returns a new promise, and errors travel down the chain until something catches them. Once those rules feel natural, async and await stop being magic. To practise, rewrite one callback-based function using promises, then fetch two endpoints with Promise.all and handle a failure properly.

Frequently asked questions

What is a promise in JavaScript?

A promise is an object representing the eventual result of asynchronous work. It starts as pending, then either fulfills with a value or rejects with a reason.

What is the difference between then and catch?

then runs when a promise fulfills, and catch runs when it rejects. catch is effectively then with only a rejection handler, and it can also catch errors thrown in earlier steps.

What is the difference between Promise.all and Promise.allSettled?

Promise.all rejects as soon as one promise rejects. Promise.allSettled always waits for all of them and reports each one’s status and value or reason.

Should I use promises or async/await?

They work together, as await is built on promises. Most code reads best with async/await, while Promise.all and similar methods remain useful for parallel work.

Do promises run in parallel?

JavaScript runs one piece of code at a time on a thread, but work like network requests happens in the background. Several of these can be in progress at once.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →