# Promises and Async/Await

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: Async Concepts
Source: https://www.devtutorials.ai/learn/javascript/async/promises-and-async-await

> What a promise is and its three states, creating promises with resolve() and reject(), then(), catch(), finally() and chaining, async functions and await with try...catch, fetch(), and Promise.all(), allSettled() and race().

## What Is a Promise?

**Promise** = an object that stands for a value that is **not ready yet**.

- It starts **pending**, then becomes **fulfilled** (a value) or **rejected** (an error).
- `then()`, `catch()` and `finally()` say what happens next.
- `async`/`await` let you write the same steps top to bottom.

**Simple lesson:** a promise is a receipt for a value that is still being made.

### A Real-World Example

At a coffee counter you get a receipt, not the coffee.
The receipt is a promise: later you get a latte (fulfilled), or "sorry, out of milk" (rejected).
A shop page does the same with `await fetch(...)`: it waits for the products without freezing.

<figure className="ts-fig">
  <svg viewBox="0 0 560 170" role="img" aria-label="A promise box starts pending in yellow, then either turns green as fulfilled with a value, or red as rejected with an error." width="100%">
    <rect x="0" y="0" width="560" height="170" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <rect x="40" y="60" width="140" height="50" rx="10" fill="#fef3c7" stroke="#d97706" />
    <text x="110" y="90" textAnchor="middle" fontSize="13" fill="#92400e">pending</text>
    <line x1="180" y1="85" x2="370" y2="45" stroke="#94a3b8" strokeWidth="2" />
    <line x1="180" y1="85" x2="370" y2="125" stroke="#94a3b8" strokeWidth="2" />
    <rect x="370" y="22" width="160" height="46" rx="10" fill="#dcfce7" stroke="#16a34a" />
    <text x="450" y="42" textAnchor="middle" fontSize="12" fill="#166534">fulfilled → then()</text>
    <text x="450" y="58" textAnchor="middle" fontSize="11" fontFamily="monospace" fill="#166534">"Latte for Asha"</text>
    <rect x="370" y="102" width="160" height="46" rx="10" fill="#fee2e2" stroke="#dc2626" />
    <text x="450" y="122" textAnchor="middle" fontSize="12" fill="#991b1b">rejected → catch()</text>
    <text x="450" y="138" textAnchor="middle" fontSize="11" fontFamily="monospace" fill="#991b1b">Error("No milk")</text>
    <circle r="7" fill="#d97706"><animate attributeName="cx" values="180;370" dur="2s" repeatCount="indefinite" /><animate attributeName="cy" values="85;45" dur="2s" repeatCount="indefinite" /></circle>
  </svg>
  <figcaption>A promise settles once: fulfilled with a value, or rejected with an error.</figcaption>
</figure>

Boxes end when their last line runs. Many end with `await new Promise((resolve) => setTimeout(resolve, 100));` so slow work has time to print. Boxes here allow top-level `await`.

## What You Will Learn

1. Promise states, and creating promises with `resolve()`/`reject()`.
2. `then()`, `catch()` and `finally()`.
3. Chaining, and replacing nested callbacks.
4. `async`, `await`, `try...catch` and `fetch()`.
5. `Promise.all()`, `allSettled()`, `race()` (and `any()`).

## Promises

[Asynchronous Fundamentals](/learn/javascript/async/asynchronous-fundamentals) used callbacks, which nest badly. Promises keep the steps flat.

### What a promise is

The promise object exists at once; its value arrives 50 ms later. The code does not wait.

```js runnable title="A promise exists straight away, and its value arrives later"
const coffee = new Promise((resolve) => {
  setTimeout(() => resolve("Latte for Asha"), 50);
});

console.log("Is it a promise?", coffee instanceof Promise);

coffee.then((drink) => {
  console.log("Now we have:", drink);
});

console.log("This line runs before the coffee is ready.");
await new Promise((resolve) => setTimeout(resolve, 100));
```

Expected output:

```text
Is it a promise? true
This line runs before the coffee is ready.
Now we have: Latte for Asha
```

### Promise states

A promise is always in one state, and moves from the first to one of the others **once**.

#### Pending

Still working, no value yet. Every promise starts here. (JavaScript does not let you read the state; this example tracks its own.)

```js runnable title="A promise stays pending until its work finishes"
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

let state = "pending";
const order = new Promise((resolve) => {
  setTimeout(() => resolve("Order 1042 packed"), 50);
});
order.then(() => {
  state = "fulfilled";
});

console.log("Straight away:", state);
await wait(100);
console.log("100 ms later:", state);
```

Expected output:

```text
Straight away: pending
100 ms later: fulfilled
```

#### Fulfilled

Finished successfully, and now holds a **value**, like `"fulfilled"` above.

#### Rejected

Failed, and holds a **reason**, usually an `Error`.

```js runnable title="A rejected promise holds an error instead of a value"
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const payment = new Promise((resolve, reject) => {
  setTimeout(() => reject(new Error("Card declined")), 20);
});

payment.catch((error) => {
  console.log("The payment was rejected:", error.message);
});

await wait(50);
```

Expected output:

```text
The payment was rejected: Card declined
```

**Settled** = fulfilled or rejected. A settled promise never changes again.

**Why "promise"?** It commits to an answer later: a value, or a reason for failing.

### Creating a promise

`new Promise(executor)`. The **executor** runs **immediately** and starts the work.

```js runnable title="The executor runs straight away and starts the work"
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const pizza = new Promise((resolve) => {
  console.log("The executor runs now. The oven is on.");
  setTimeout(() => resolve("Margherita pizza"), 30);
});

console.log("The promise has been created.");
pizza.then((food) => console.log("Delivered:", food));

await wait(60);
```

Expected output:

```text
The executor runs now. The oven is on.
The promise has been created.
Delivered: Margherita pizza
```

### `resolve()` and `reject()`

- `resolve(value)` fulfills the promise.
- `reject(error)` rejects it.

```js runnable title="One function that can succeed or fail"
function checkStock(item, quantity) {
  return new Promise((resolve, reject) => {
    const stock = { croissant: 4, muffin: 0 };
    setTimeout(() => {
      if (stock[item] >= quantity) {
        resolve(`${quantity} ${item}(s) reserved`);
      } else {
        reject(new Error(`Not enough ${item} in stock`));
      }
    }, 10);
  });
}

checkStock("croissant", 2).then((message) => console.log("Success:", message));
checkStock("muffin", 1).catch((error) => console.log("Failure:", error.message));

await new Promise((resolve) => setTimeout(resolve, 50));
```

Expected output:

```text
Success: 2 croissant(s) reserved
Failure: Not enough muffin in stock
```

Only the **first** call counts; later calls are ignored:

```js runnable title="Only the first call to resolve or reject counts"
const ticket = new Promise((resolve, reject) => {
  resolve("Seat 12A");
  resolve("Seat 30F");
  reject(new Error("Flight cancelled"));
});

console.log("Your seat:", await ticket);
```

Expected output:

```text
Your seat: Seat 12A
```

Reject with `new Error("...")`, not a string. An `Error` carries a message and a stack trace.

### `then()`

The **handler** you pass runs when the promise is fulfilled, and receives the value.

```js runnable title="then() receives the value once it is ready"
const getPrice = new Promise((resolve) => {
  setTimeout(() => resolve(4.5), 20);
});

getPrice.then((price) => {
  console.log(`A latte costs $${price}`);
});

await new Promise((resolve) => setTimeout(resolve, 50));
```

Expected output:

```text
A latte costs $4.5
```

### `catch()`

Runs when the promise is rejected. A rejection skips past `then()` handlers straight to `catch()`.

```js runnable title="catch() receives the error when the promise is rejected"
const login = new Promise((resolve, reject) => {
  setTimeout(() => reject(new Error("Wrong password for ravi@example.com")), 20);
});

login
  .then((user) => console.log("Welcome,", user))
  .catch((error) => console.log("Login failed:", error.message));

await new Promise((resolve) => setTimeout(resolve, 50));
```

Expected output:

```text
Login failed: Wrong password for ravi@example.com
```

### `finally()`

Runs after success **or** failure, with no value. Use it to tidy up, like hiding "Loading...".

```js runnable title="finally() runs after success and after failure"
function loadMenu(shouldFail) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (shouldFail) reject(new Error("Menu server is down"));
      else resolve(["Latte", "Mocha", "Chai"]);
    }, 10);
  });
}

async function show(shouldFail) {
  console.log("Loading...");
  await loadMenu(shouldFail)
    .then((menu) => console.log("Menu:", menu.join(", ")))
    .catch((error) => console.log("Error:", error.message))
    .finally(() => console.log("Hide the loading message"));
}

await show(false);
await show(true);
```

Expected output:

```text
Loading...
Menu: Latte, Mocha, Chai
Hide the loading message
Loading...
Error: Menu server is down
Hide the loading message
```

## Promise chaining

`then()` returns a new promise, so you can chain steps. Each waits for the one before.

### Multiple `then()` calls

```js runnable title="Three steps that run in order"
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

await wait(10)
  .then(() => console.log("Step 1: take the order"))
  .then(() => console.log("Step 2: make the drink"))
  .then(() => console.log("Step 3: call out the name"));
```

Expected output:

```text
Step 1: take the order
Step 2: make the drink
Step 3: call out the name
```

### Passing data from one step to another

What a handler **returns** becomes the next step's value. If it returns a promise, the chain waits for it.

```js runnable title="Each step receives what the previous step returned"
const cart = [
  { name: "Latte", price: 4.5, qty: 2 },
  { name: "Muffin", price: 3.25, qty: 1 },
];

const total = await Promise.resolve(cart)
  .then((items) => items.map((item) => item.price * item.qty))
  .then((lineTotals) => lineTotals.reduce((sum, amount) => sum + amount, 0))
  .then((subtotal) => subtotal * 1.1)
  .then((withTax) => withTax.toFixed(2));

console.log("Total to pay:", total);
```

Expected output:

```text
Total to pay: 13.48
```

Forget `return`, and the next step gets `undefined`, maybe before the slow work is done.

### Replacing nested callbacks with chaining

Nested callbacks drift right:

```js runnable title="Three dependent steps written with nested callbacks"
function findCustomer(email, done) {
  setTimeout(() => done({ id: 7, name: "Asha" }), 10);
}
function findLastOrder(customerId, done) {
  setTimeout(() => done({ id: 1042, customerId }), 10);
}
function findItems(orderId, done) {
  setTimeout(() => done(["Latte", "Muffin"]), 10);
}

findCustomer("asha@example.com", (customer) => {
  findLastOrder(customer.id, (order) => {
    findItems(order.id, (items) => {
      console.log(`${customer.name} last ordered: ${items.join(", ")}`);
    });
  });
});

await new Promise((resolve) => setTimeout(resolve, 60));
```

The same steps with functions that return promises stay flat:

```js runnable title="The same three steps as a flat promise chain"
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const findCustomer = (email) => wait(10).then(() => ({ id: 7, name: "Asha" }));
const findLastOrder = (customerId) => wait(10).then(() => ({ id: 1042, customerId }));
const findItems = (orderId) => wait(10).then(() => ["Latte", "Muffin"]);

await findCustomer("asha@example.com")
  .then((customer) => findLastOrder(customer.id))
  .then((order) => findItems(order.id))
  .then((items) => console.log(`Last order: ${items.join(", ")}`));
```

Expected output:

```text
Last order: Latte, Muffin
```

## Async/await

`async`/`await` are a friendlier way to use the **same** promises.

### `async` function

An `async` function **always returns a promise**, even when it returns a plain value.

```js runnable title="An async function always hands back a promise"
async function getGreeting() {
  return "Good morning, Ravi";
}

const result = getGreeting();
console.log("Is the result a promise?", result instanceof Promise);
console.log("Its value:", await result);
```

Expected output:

```text
Is the result a promise? true
Its value: Good morning, Ravi
```

### `await` keyword

`await` pauses the async function until the promise settles, then gives its value. Only that function pauses; the page does not freeze.

```js runnable title="await pauses until the value is ready"
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function brewCoffee() {
  console.log("Grinding beans...");
  await wait(20);
  console.log("Pouring water...");
  await wait(20);
  return "Flat white";
}

const drink = await brewCoffee();
console.log("Ready:", drink);
```

Expected output:

```text
Grinding beans...
Pouring water...
Ready: Flat white
```

The callback-hell steps with `await` read like a recipe:

```js runnable title="The same three steps, written with await"
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const findCustomer = (email) => wait(10).then(() => ({ id: 7, name: "Asha" }));
const findLastOrder = (customerId) => wait(10).then(() => ({ id: 1042, customerId }));
const findItems = (orderId) => wait(10).then(() => ["Latte", "Muffin"]);

async function lastOrderSummary(email) {
  const customer = await findCustomer(email);
  const order = await findLastOrder(customer.id);
  const items = await findItems(order.id);
  return `${customer.name} last ordered: ${items.join(", ")}`;
}

console.log(await lastOrderSummary("asha@example.com"));
```

Expected output:

```text
Asha last ordered: Latte, Muffin
```

`async` functions return promises. `await` unwraps a promise into its value.

### Promise return behaviour

- Return a value → the promise is fulfilled with it.
- Throw an error → the promise is rejected with it.
- Return a promise → it follows that promise (never a promise inside a promise).

```js runnable title="return fulfills, throw rejects"
async function applyCoupon(code) {
  if (code === "WELCOME10") {
    return 10;
  }
  throw new Error(`Coupon ${code} is not valid`);
}

applyCoupon("WELCOME10").then((percent) => console.log("Discount:", percent + "%"));
applyCoupon("FREECAKE").catch((error) => console.log("Rejected:", error.message));

await new Promise((resolve) => setTimeout(resolve, 10));
```

Expected output:

```text
Discount: 10%
Rejected: Coupon FREECAKE is not valid
```

### Error handling with `try...catch`

If an awaited promise rejects, `await` **throws**, and `catch` gets the error. `finally` works as usual.

```js runnable title="try...catch handles a failed await"
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function chargeCard(amount) {
  await wait(10);
  if (amount > 100) throw new Error("Card limit is $100");
  return `Charged $${amount}`;
}

async function checkout(amount) {
  try {
    const receipt = await chargeCard(amount);
    console.log("Success:", receipt);
  } catch (error) {
    console.log("Payment failed:", error.message);
  } finally {
    console.log("Checkout finished for $" + amount);
  }
}

await checkout(40);
await checkout(250);
```

Expected output:

```text
Success: Charged $40
Checkout finished for $40
Payment failed: Card limit is $100
Checkout finished for $250
```

`try...catch` only catches promises that are **awaited inside** the `try`. Without `await`, the error escapes.

### Using `fetch()`

`fetch()` loads data from a URL and returns a promise. A real call needs a live server:

```js
const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
const user = await response.json();
console.log(user.name);
```

The boxes have no internet, but a **data URL** carries its content inside itself:

```js runnable title="fetch() with await, using a data URL instead of a server"
async function loadUser() {
  const response = await fetch('data:application/json,{"id":1,"name":"Asha","city":"Chennai"}');
  const user = await response.json();
  return user;
}

const user = await loadUser();
console.log(`${user.name} lives in ${user.city}`);
```

Expected output:

```text
Asha lives in Chennai
```

Two `await`s: one for the response, one for reading its body. **Fetch API** covers more.

## Working with multiple promises

### Handling more than one async task

Independent tasks should run **at the same time**, not one after another.

```js runnable title="One after another, compared with both at once"
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const log = [];

async function make(item, ms) {
  log.push(`start ${item}`);
  await wait(ms);
  log.push(`finish ${item}`);
  return item;
}

await make("latte", 30);
await make("bagel", 10);
console.log("One after another:", log.join(" | "));

log.length = 0;
await Promise.all([make("latte", 30), make("bagel", 10)]);
console.log("Both at once:     ", log.join(" | "));
```

Expected output:

```text
One after another: start latte | finish latte | start bagel | finish bagel
Both at once:      start latte | start bagel | finish bagel | finish latte
```

### `Promise.all()`

Waits for **all** to fulfill. The result array keeps the **input order**.

```js runnable title="Promise.all() returns every value, in input order"
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));

const prices = await Promise.all([
  wait(30, 4.5),
  wait(10, 3.25),
  wait(20, 2.75),
]);

console.log("Prices:", prices);
console.log("Total:", prices.reduce((sum, price) => sum + price, 0));
```

Expected output:

```text
Prices: [
  4.5,
  3.25,
  2.75
]
Total: 10.5
```

If **any** promise rejects, the whole thing rejects at once:

```js runnable title="One failure rejects the whole Promise.all()"
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fail = (ms, message) => new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));

try {
  await Promise.all([wait(20, "Latte"), fail(10, "Out of oat milk"), wait(30, "Bagel")]);
} catch (error) {
  console.log("Promise.all() failed:", error.message);
}
```

Expected output:

```text
Promise.all() failed: Out of oat milk
```

### `Promise.allSettled()`

Waits for every promise and **never rejects**. Each entry has `status` (`"fulfilled"`/`"rejected"`) and a `value` or `reason`.

```js runnable title="Promise.allSettled() reports every outcome"
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fail = (ms, message) => new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));

const results = await Promise.allSettled([
  wait(10, "Email sent to Asha"),
  fail(20, "Email to Ravi bounced"),
  wait(15, "Email sent to Meera"),
]);

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

Expected output:

```text
OK:     Email sent to Asha
FAILED: Email to Ravi bounced
OK:     Email sent to Meera
```

### `Promise.race()`

Settles with the **first** promise to settle. Common use: a time limit.

```js runnable title="Promise.race() used as a time limit"
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));

function withTimeLimit(task, ms) {
  const timer = new Promise((_, reject) => {
    setTimeout(() => reject(new Error(`Gave up after ${ms} ms`)), ms);
  });
  return Promise.race([task, timer]);
}

try {
  console.log(await withTimeLimit(wait(10, "Quick answer"), 50));
  console.log(await withTimeLimit(wait(100, "Slow answer"), 30));
} catch (error) {
  console.log("Error:", error.message);
}
```

Expected output:

```text
Quick answer
Error: Gave up after 30 ms
```

**Why "race"?** The first to finish wins.

`Promise.any()` waits for the first promise that **fulfills**, ignoring failures until all have failed.

## Promises on a Web Page

`await` a pretend server for three products **at once** with `Promise.all()`, show "Loading..." while waiting, and handle a failure with `try...catch...finally`.

```js runnable preview="product-list" title="Loading products with async and await"
const list = document.querySelector("#products");
const status = document.querySelector("#status");
const search = document.querySelector("#search");
search.placeholder = "Type fail to make one request fail";

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function getProduct(id, shouldFail) {
  await wait(300 + id * 100);
  if (shouldFail && id === 2) throw new Error("Product 2 could not be loaded");
  return { id, name: ["Notebook", "Steel bottle", "Lunch box"][id - 1] };
}

async function load() {
  status.textContent = "Loading...";
  list.innerHTML = "";
  try {
    const products = await Promise.all([1, 2, 3].map((id) => getProduct(id, search.value === "fail")));
    for (const product of products) {
      const li = document.createElement("li");
      li.textContent = `#${product.id} ${product.name}`;
      list.append(li);
    }
    status.textContent = `${products.length} products loaded`;
  } catch (error) {
    status.textContent = "Error: " + error.message;
  } finally {
    console.log("finished loading at", new Date().toISOString().slice(11, 19));
  }
}

search.addEventListener("change", load);
load();
```

Type `fail` in the box and press Enter. `Promise.all()` rejects, and `catch` shows the message.

**Easy way to remember:** `then` = when it works, `catch` = when it fails, `finally` = either way. `await` = "wait here for the value".

## TL;DR

- Promise states: pending → fulfilled (value) or rejected (error), once.
- `new Promise((resolve, reject) => ...)`; the executor runs at once.
- Chain with `then()`, and always `return` what the next step needs.
- `async` returns a promise; `await` unwraps it; use `try...catch` around awaits.
- `all` needs every success; `allSettled` reports all; `race` takes the first.

## Try this

In the `Promise.all()` failure example, change `fail(10, "Out of oat milk")` to `wait(10, "Muffin")` and log the result. You get all three values, in input order.

## Check Yourself

## Common mistakes

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| Calling an async function without `await` | It returns the data | It returns a promise | Properties are `undefined` |
| A `then()` handler with no `return` | The value passes on | Return it explicitly | The next step gets `undefined` |
| `try` around an un-awaited call | `try` sees all errors | Only awaited ones | The rejection escapes |
| Awaiting independent tasks one by one | It is the same speed | Start them together | Three times slower |
| `Promise.all()` when some may fail | It keeps the good results | It rejects on the first failure | All results are lost |
| Calling `resolve()` twice | The value updates | Only the first call counts | The second is ignored |

## Quick reference

<div className="tscroll">

| Syntax | Meaning |
|---|---|
| `new Promise((resolve, reject) => { ... })` | create a promise, and start its work in the executor |
| `resolve(value)` | fulfill the promise with a value |
| `reject(new Error("..."))` | reject the promise with a reason |
| `promise.then(value => ...)` | run a handler when the promise is fulfilled |
| `promise.catch(error => ...)` | run a handler when the promise is rejected |
| `promise.finally(() => ...)` | run a handler when the promise settles either way |
| `Promise.resolve(value)` | a promise that is already fulfilled |
| `async function name() { ... }` | a function that always returns a promise |
| `const value = await promise;` | pause the async function until the promise settles |
| `try { await ... } catch (error) { ... }` | handle a rejected promise with ordinary error handling |
| `await Promise.all([a, b])` | wait for every promise; reject on the first failure |
| `await Promise.allSettled([a, b])` | wait for every promise; report each outcome, never reject |
| `await Promise.race([a, b])` | settle with whichever promise settles first |

</div>

## Exercises

## What to Remember

- A promise is a value that arrives later.
- `await` makes async code read top to bottom.
- Run independent work together with `Promise.all()` or `allSettled()`.

Next: **Fetch API**. Call web APIs with `fetch()`, read responses, send requests, and handle errors.
