Promises and Async/Await

By Syncfusion®, Inc. · Last updated

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.

pending

fulfilled → then() "Latte for Asha"

rejected → catch() Error("No milk")

A promise settles once: fulfilled with a value, or rejected with an error.

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 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.

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:

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.)

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:

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.

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:

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.

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:

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.

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:

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

Only the first call counts; later calls are ignored:

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:

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.

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:

A latte costs $4.5

catch()

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

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:

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...".

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:

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

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:

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.

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:

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:

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:

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:

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.

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:

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.

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:

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

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

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:

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).

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:

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.

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:

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:

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:

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:

Asha lives in Chennai

Two awaits: 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.

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:

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.

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:

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

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

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:

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.

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:

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.

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:

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.

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

MistakeWrong ideaCorrect ideaWhat goes wrong
Calling an async function without awaitIt returns the dataIt returns a promiseProperties are undefined
A then() handler with no returnThe value passes onReturn it explicitlyThe next step gets undefined
try around an un-awaited calltry sees all errorsOnly awaited onesThe rejection escapes
Awaiting independent tasks one by oneIt is the same speedStart them togetherThree times slower
Promise.all() when some may failIt keeps the good resultsIt rejects on the first failureAll results are lost
Calling resolve() twiceThe value updatesOnly the first call countsThe second is ignored

Quick reference

SyntaxMeaning
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

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.