JavaScript Promises Explained: then, async/await and Promise.all

By Marko Denic
Contents
  1. Creating a promise
  2. then, catch and finally
  3. Chaining
  4. async and await
  5. The same request with await
  6. Running promises in parallel
  7. Promise.all: wait for all, fail fast
  8. Promise.allSettled: wait for all, never fail
  9. Promise.race and Promise.any
  10. Common mistakes
  11. Forgetting to return inside then
  12. await inside forEach
  13. Missing error handling
  14. When does then run?
  15. FAQ

Short answer: a promise is an object that stands for a value you’ll get later, like the response to a network request. It starts out pending, then settles once: fulfilled with a value, or rejected with an error. You react to the result with .then() and .catch(), or more readably with async/await.

Below: how to create and use promises, how errors flow, how to run several at once, and the mistakes that cause most promise bugs. The API URLs and helper names in the examples are placeholders, so swap in your own.

Creating a promise

You’ll mostly use promises that functions like fetch() return. When you need your own, for example to wrap a callback-based API, pass a function to new Promise(). It receives resolve to fulfill the promise and reject to fail it. Whichever is called first wins; later calls are ignored.

javascript
function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

wait(1000).then(() => console.log('One second later'));

const coinFlip = new Promise((resolve, reject) => {
  if (Math.random() < 0.5) {
    resolve('heads');
  } else {
    reject(new Error('tails'));
  }
});

then, catch and finally

.then() runs when the promise is fulfilled, .catch() when it’s rejected, and .finally() in both cases, which makes it the place to hide a loading spinner. Each of them returns a new promise, so you can chain them.

javascript
coinFlip
  .then((result) => console.log('Won with', result))
  .catch((error) => console.log('Lost:', error.message))
  .finally(() => console.log('Game over'));

Chaining

Whatever you return from .then() becomes the value for the next one. If you return a promise, the chain waits for it. One .catch() at the end handles an error from any step.

javascript
fetch('/api/user')
  .then((response) => response.json())
  .then((user) => fetch(`/api/posts?user=${user.id}`))
  .then((response) => response.json())
  .then((posts) => console.log(posts))
  .catch((error) => console.error('Something failed:', error));

async and await

async/await is built on promises and reads like normal step-by-step code. An async function always returns a promise. Inside it, await pauses the function until a promise settles, then gives you its value, or throws its error so a regular try/catch can handle it.

The same request with await

One thing to know about fetch(): it only rejects on network failures. A 404 or 500 response still fulfills, so check response.ok yourself and throw. The HTTP status codes guide explains what each code means.

javascript
async function getJSON(url) {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`HTTP ${response.status} for ${url}`);
  }
  return response.json();
}

async function loadPosts() {
  try {
    const user = await getJSON('/api/user');
    const posts = await getJSON(`/api/posts?user=${user.id}`);
    console.log(posts);
  } catch (error) {
    console.error('Could not load posts:', error.message);
  }
}

loadPosts();

You can use await at the top level of a JavaScript module (<script type="module">) and in the browser console. In a classic script, it only works inside an async function.

Running promises in parallel

await one after another runs the requests in sequence: the second only starts when the first is done. When they don’t depend on each other, start them together with one of these four methods.

Promise.all: wait for all, fail fast

Fulfills with an array of results, in the same order as the input. If any promise rejects, the whole thing rejects right away with that error. Use it when you need every result.

javascript
const [user, stats] = await Promise.all([
  getJSON('/api/user'),
  getJSON('/api/stats'),
]);

Promise.allSettled: wait for all, never fail

Waits for every promise and tells you how each one ended. Use it when some requests are allowed to fail, like loading several dashboard widgets.

javascript
const results = await Promise.allSettled([
  getJSON('/api/user'),
  getJSON('/api/missing'),
]);

for (const result of results) {
  if (result.status === 'fulfilled') {
    console.log('OK:', result.value);
  } else {
    console.log('Failed:', result.reason.message);
  }
}

Promise.race and Promise.any

Promise.race() settles with the first promise to settle, whether it fulfills or rejects. That makes it handy for timeouts. Promise.any() waits for the first one to fulfill and only rejects if all of them fail, which suits mirrors or fallback servers.

For fetch() specifically, fetch(url, { signal: AbortSignal.timeout(5000) }) is a better timeout, because it also cancels the request.

javascript
function withTimeout(promise, ms) {
  const timeout = new Promise((_, reject) =>
    setTimeout(() => reject(new Error(`Timed out after ${ms} ms`)), ms)
  );
  return Promise.race([promise, timeout]);
}

const stats = await withTimeout(getJSON('/api/stats'), 5000);

const fastest = await Promise.any([
  getJSON('https://mirror-1.example.com/data.json'),
  getJSON('https://mirror-2.example.com/data.json'),
]);

Common mistakes

Forgetting to return inside then

Without return, the next step gets undefined, and the chain doesn’t wait for the inner promise. Arrow functions without braces return automatically; with braces, they don’t.

javascript
// Bug: braces, no return
fetch('/api/user').then((response) => { response.json(); })
  .then((user) => console.log(user)); // undefined

// Fixed
fetch('/api/user').then((response) => response.json())
  .then((user) => console.log(user));

await inside forEach

forEach doesn’t wait for async callbacks, so the code after it runs before they finish. Use for...of to run them one by one, or Promise.all with map to run them in parallel.

javascript
// Doesn't wait
ids.forEach(async (id) => {
  await save(id);
});
console.log('Done?'); // runs before the saves finish

// One by one
for (const id of ids) {
  await save(id);
}

// All at once
await Promise.all(ids.map((id) => save(id)));

Missing error handling

A rejected promise with no .catch() or try/catch becomes an “Uncaught (in promise)” error in the console, and in Node.js it crashes the process by default. Every chain needs a .catch() at the end, and every await that can fail needs a try/catch somewhere above it.

When does then run?

Promise callbacks never run immediately, even for a promise that’s already resolved. They’re queued as microtasks, which run after the current code finishes but before timers like setTimeout. Animation work belongs in requestAnimationFrame, which runs before the next repaint.

javascript
console.log('1');
setTimeout(() => console.log('4: timer'), 0);
Promise.resolve().then(() => console.log('3: microtask'));
console.log('2');

FAQ

What is the difference between a promise and async/await?

They’re the same mechanism. async/await is a nicer way to write code that uses promises: an async function returns a promise, and await waits for one.

Can a promise be cancelled?

No. A promise only represents a result. To cancel the work behind it, like a fetch() request, pass an AbortController signal to the function that does the work.

Is a promise synchronous or asynchronous?

The function you pass to new Promise() runs immediately and synchronously. The .then() callbacks always run asynchronously, after the current code finishes.

What does “Uncaught (in promise)” mean?

A promise was rejected and nothing handled the error. Add a .catch() to the chain or wrap the await in try/catch.

Should I use Promise.all or a for loop with await?

Promise.all when the tasks are independent, because they run at the same time. A for...of loop when each step needs the previous result, or when you must limit how many requests hit a server at once.

New to how requests work? HTTP methods explains GET, POST and the rest, and URLSearchParams shows how to build query strings for fetch().