---
title: "JavaScript – Promises and async/await"
url: https://www.khanwaseem.com/blog/javascript-tutorial/javascript-promises-and-async-await
author: "khan Waseem"
published: 2026-11-25
updated: 2026-11-25
topics: ["Javascript Tutorial", "course"]
description: "Understand asynchronous JavaScript: why callbacks lead to callback hell, how Promises work, writing clean code with async/await and try/catch, running tasks in parallel with Promise.all, allSettled, race and any, and…"
---

# JavaScript – Promises and async/await

Table of Contents

[Toggle](#)

- [Introduction:](#introduction)
- [The Problem with Callbacks](#the-problem-with-callbacks)
- [What Is a Promise?](#what-is-a-promise)[1. Creating a Promise:](#1-creating-a-promise)
- [2. Using a Promise: then, catch and finally:](#2-using-a-promise-then-catch-and-finally)
- [3. Chaining:](#3-chaining)

- [async and await](#async-and-await)
- [A Real Example: fetch](#a-real-example-fetch)
- [Running Tasks in Parallel](#running-tasks-in-parallel)[1. Promise.all:](#1-promiseall)
- [2. Promise.allSettled:](#2-promiseallsettled)
- [3. Promise.race:](#3-promiserace)
- [4. Promise.any:](#4-promiseany)

- [How It Works: The Microtask Queue](#how-it-works-the-microtask-queue)
- [Common Mistakes](#common-mistakes)[1. Forgetting await:](#1-forgetting-await)
- [2. Using await inside forEach:](#2-using-await-inside-foreach)
- [3. Not handling errors:](#3-not-handling-errors)
- [4. Awaiting independent tasks one by one:](#4-awaiting-independent-tasks-one-by-one)

- [Conclusion:](#conclusion)

## Introduction:

JavaScript runs your code on a **single thread**: it can only do one thing at a time. Yet web pages load data from servers, wait for timers, read files and respond to clicks, all without freezing. The secret is **asynchronous** code: JavaScript starts a slow task, carries on with other work, and comes back to handle the result when it is ready.

Think of ordering coffee at a café. You order, get a receipt, and go read a book. When the coffee is ready, they call your name. You don’t stand frozen at the counter.

```javascript
console.log("1. Order a coffee");
setTimeout(() => console.log("3. Coffee is ready"), 1000);
console.log("2. Read a book while waiting");

// 1. Order a coffee
// 2. Read a book while waiting
// 3. Coffee is readyCode language: JavaScript (javascript)
```

In the [JavaScript Functions](https://blog.khanwaseem.com/javascript-functions/) and [Events](https://blog.khanwaseem.com/javascript-events/) lessons we passed functions to be called later. In this lesson we will see how asynchronous code evolved from **callbacks** to **Promises** to **async/await**, which is how modern JavaScript is written today.

## The Problem with Callbacks

The oldest way to handle async results is a **callback**: a function you pass in, which is called when the work is done. Node.js style callbacks take an error as the first argument.

Now imagine three steps that depend on each other: load a user, then their orders, then the invoice for the first order.

```javascript
getUser(1, (err, user) => {
  if (err) return console.error(err);
  getOrders(user, (err, orders) => {
    if (err) return console.error(err);
    getInvoice(orders[0], (err, invoice) => {
      if (err) return console.error(err);
      console.log(invoice); // { orderId: 7, paid: true }
    });
  });
});Code language: JavaScript (javascript)
```

Each step goes one level deeper, and every level must handle its own errors. With more steps this becomes the famous **callback hell** (or “pyramid of doom”): hard to read, easy to get wrong, and painful to change.

## What Is a Promise?

A **Promise** is an object that represents a value that will be available **later**: like the receipt you get at the café. A Promise is always in one of three states:

- **Pending:** the work is still going on.

- **Fulfilled:** the work finished successfully, and the Promise has a **value**.

- **Rejected:** the work failed, and the Promise has a **reason** (usually an `Error`).

Once a Promise is fulfilled or rejected, it is **settled** and never changes again.

### 1. Creating a Promise:

You create a Promise with `new Promise`, passing a function that receives two functions: `resolve` (call it with the result) and `reject` (call it with an error).

```javascript
function getUser(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (id <= 0) reject(new Error("Invalid user id"));
      else resolve({ id, name: "Sara" });
    }, 100);
  });
}Code language: JavaScript (javascript)
```

In practice you will create Promises yourself only occasionally, usually to wrap old callback-based code. Most of the time you **use** Promises returned by APIs such as `fetch`.

A useful small helper that turns `setTimeout` into a Promise:

```javascript
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));Code language: JavaScript (javascript)
```

### 2. Using a Promise: then, catch and finally:

- **`.then(fn)`** runs when the Promise is fulfilled and receives the value.

- **`.catch(fn)`** runs when it is rejected and receives the error.

- **`.finally(fn)`** runs in both cases, which is good for cleanup such as hiding a loading spinner.

```javascript
getUser(0)
  .then((user) => console.log(user))
  .catch((err) => console.log("Caught:", err.message));

// Caught: Invalid user idCode language: JavaScript (javascript)
```

### 3. Chaining:

The real power of `.then()` is that it **returns a new Promise**. If your function returns a value or another Promise, the next `.then()` receives its result. This flattens callback hell into a straight line:

```javascript
getUser(1)
  .then((user) => getOrders(user))
  .then((orders) => getInvoice(orders[0]))
  .then((invoice) => console.log(invoice))
  .catch((err) => console.error("Something failed:", err.message))
  .finally(() => console.log("done"));

// { orderId: 7, paid: true }
// doneCode language: JavaScript (javascript)
```

One `.catch()` at the end handles an error from **any** step in the chain. Compare that with three separate `if (err)` checks in the callback version.

## async and await

Promise chains are much better than callbacks, but **async/await**, added in ES2017, makes async code read almost like normal, step-by-step code.

- Put **`async`** before a function. An async function **always returns a Promise**.

- Inside it, put **`await`** before a Promise. The function pauses at that line until the Promise settles, then continues with its value. While it is paused, the rest of your program keeps running.

- Handle errors with an ordinary **`try...catch`**.

```javascript
async function showInvoice(userId) {
  try {
    const user = await getUser(userId);
    const orders = await getOrders(user);
    const invoice = await getInvoice(orders[0]);
    console.log(invoice);
    return invoice;
  } catch (err) {
    console.log("Error:", err.message);
  } finally {
    console.log("done");
  }
}

showInvoice(1);   // { orderId: 7, paid: true }  then  done
showInvoice(-1);  // Error: Invalid user id      then  doneCode language: JavaScript (javascript)
```

This does exactly the same as the chain above, but it reads from top to bottom, and you can use normal `if`, loops and variables between the steps.

Remember that an `async` function returns a Promise, even when you return a plain value:

```javascript
async function hello() {
  return "hi";
}

console.log(hello());      // Promise { 'hi' }
hello().then(console.log); // hiCode language: JavaScript (javascript)
```

## A Real Example: fetch

The browser’s `fetch` function (also built into Node.js 18 and later) returns a Promise, so it works naturally with `await`. One important detail: `fetch` only rejects on **network** errors. An HTTP error such as 404 or 500 still fulfills the Promise, so you must check `response.ok` yourself.

```javascript
async function loadUser(id) {
  const response = await fetch(`/api/users/${id}`);
  if (!response.ok) {
    throw new Error(`Request failed with status ${response.status}`);
  }
  return response.json(); // also returns a Promise
}

try {
  const user = await loadUser(1);
  console.log(user); // { id: 1, name: 'Sara' }
  await loadUser(2);
} catch (err) {
  console.log(err.message); // Request failed with status 404
}Code language: JavaScript (javascript)
```

(Using `await` outside a function, as in the last block, works in ES modules and the browser console. In a regular script, put it inside an `async` function.)

## Running Tasks in Parallel

`await` waits for each Promise before starting the next line. That is what you want when a step **depends** on the previous one. But if the tasks are independent, waiting for each one in turn wastes time:

```javascript
async function sequential() {
  const a = await wait(300, "profile");
  const b = await wait(300, "orders");
  const c = await wait(300, "reviews");
  return [a, b, c];
}
// sequential: about 900 msCode language: JavaScript (javascript)
```

(Here `wait(ms, value)` is a version of our helper that resolves with `value` after `ms` milliseconds.)

Start all of them at once and wait for them together with **`Promise.all`**:

```javascript
async function parallel() {
  const [a, b, c] = await Promise.all([
    wait(300, "profile"),
    wait(300, "orders"),
    wait(300, "reviews"),
  ]);
  return [a, b, c];
}
// parallel: about 300 ms, three times fasterCode language: JavaScript (javascript)
```

JavaScript has four tools for combining Promises:

### 1. Promise.all:

Waits for **all** Promises and returns their values in the same order. If **any** of them rejects, `Promise.all` rejects immediately with that error.

```javascript
try {
  await Promise.all([wait(100, "ok"), fail(50, "orders service down")]);
} catch (e) {
  console.log(e.message); // orders service down
}Code language: JavaScript (javascript)
```

### 2. Promise.allSettled:

Waits for all of them, whether they succeed or fail, and tells you what happened to each one. Use it when one failure shouldn’t throw away the other results, such as a dashboard loading several independent widgets.

```javascript
const results = await Promise.allSettled([wait(100, "ok"), fail(50, "orders service down")]);
console.log(results.map((r) => (r.status === "fulfilled" ? r.value : r.reason.message)));
// [ 'ok', 'orders service down' ]Code language: JavaScript (javascript)
```

### 3. Promise.race:

Settles as soon as the **first** Promise settles, whether it succeeds or fails.

```javascript
console.log(await Promise.race([wait(200, "slow server"), wait(100, "fast server")]));
// fast serverCode language: JavaScript (javascript)
```

A classic use is adding a **timeout** to any Promise:

```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]);
}

try {
  await withTimeout(wait(1000, "data"), 200);
} catch (e) {
  console.log(e.message); // Timed out after 200 ms
}Code language: JavaScript (javascript)
```

### 4. Promise.any:

Fulfills with the **first successful** result and ignores failures (it rejects only if all of them fail). Useful for trying several mirrors or servers and using whichever answers first.

```javascript
console.log(await Promise.any([fail(50, "mirror 1 down"), wait(150, "mirror 2"), wait(250, "mirror 3")]));
// mirror 2Code language: JavaScript (javascript)
```

## How It Works: The Microtask Queue

When a Promise settles, its `.then()` callback (or the rest of an `async` function after `await`) is not run immediately. It is put in a queue called the **microtask queue**, which JavaScript empties as soon as the current code finishes, **before** timers such as `setTimeout`. That’s why this prints in a surprising order:

```javascript
console.log("A");
setTimeout(() => console.log("B (timeout)"), 0);
Promise.resolve().then(() => console.log("C (promise)"));
console.log("D");

// A
// D
// C (promise)
// B (timeout)Code language: JavaScript (javascript)
```

We will look at this in much more detail in a later lesson about the JavaScript **event loop**.

## Common Mistakes

### 1. Forgetting await:

Without `await` you get the Promise itself, not its value: `const user = getUser(1)` gives `Promise { <pending> }`, and `user.name` is `undefined`.

### 2. Using await inside forEach:

`forEach` does not wait for async callbacks. The code after it runs before any of them finish:

```javascript
const ids = [1, 2, 3];

const out1 = [];
ids.forEach(async (id) => { out1.push(await wait(50, id * 10)); });
console.log(out1); // []  <- nothing yet!

const out2 = [];
for (const id of ids) out2.push(await wait(50, id * 10)); // one after another
console.log(out2); // [ 10, 20, 30 ]

console.log(await Promise.all(ids.map((id) => wait(50, id * 10)))); // all at once
// [ 10, 20, 30 ]Code language: JavaScript (javascript)
```

Use `for...of` when the steps must run in order, and `Promise.all` with `map` when they can run in parallel.

### 3. Not handling errors:

A rejected Promise with no `.catch()` or `try...catch` causes an “unhandled promise rejection” warning in the browser, and in Node.js it crashes the process by default. Always handle errors, at least at the top level.

### 4. Awaiting independent tasks one by one:

If the tasks don’t depend on each other, start them together with `Promise.all`, as shown above.

## Conclusion:

Asynchronous code lets JavaScript start slow tasks and keep working while it waits. Callbacks were the first solution but quickly lead to deeply nested code. A **Promise** represents a future value that is pending, fulfilled or rejected, and can be chained with `.then()`, `.catch()` and `.finally()`. **async/await** builds on Promises and lets you write async code that reads top to bottom, with `try...catch` for errors. Use `Promise.all`, `allSettled`, `race` and `any` to run several tasks at once, and avoid the common traps: a missing `await`, `await` inside `forEach`, and unhandled errors.

In the next JavaScript lesson we will look at **closures and scope**, which explain how functions remember the variables around them.

### Related posts:

[Incremental Static Regeneration (ISR) in Next.js](https://blog.khanwaseem.com/incremental-static-regeneration-isr-in-next-js/)
[Data Fetching in Next.js](https://blog.khanwaseem.com/data-fetching-in-next-js/)
[JavaScript – Errors & Exceptions Handling](https://blog.khanwaseem.com/javascript-errors-exceptions-handling/)
[API Routes in Next.js](https://blog.khanwaseem.com/api-routes-in-next-js/)

Powered by [YARPP](https://yarpp.com).
