TalentJR

🟨 JavaScript tutorial for beginners · Class 9 · Lesson 13 of 18 · Free

Async/Await Deep Dive – Write Clean Asynchronous JavaScript

⏱ About 35 minutes · ▶ run real JavaScript here — nothing to install · no sign-in

In this lesson you will

  • Explain what async and await do, step by step
  • Handle errors in async code with try, catch and finally
  • Run several waits at the same time with Promise.all

Your mother asks you to boil water for tea, set the table and fetch the newspaper. You do not stand and stare at the kettle — you set the table while the water boils. JavaScript works the same way, and async/await lets you write this "wait, but don't freeze" code so it reads like a simple recipe.

What does async/await do in JavaScript?

In Lesson 3 you met promises: a promise is a "I will give you the answer later" box. `await` means: pause this function until the promise has its answer, then go on.

You can only use `await` inside a function marked `async` (or at the top of a module, like our Run box). While one async function is paused, the rest of the program keeps running.

The `wait(ms)` helper below makes a promise that finishes after some milliseconds. We use it to pretend something is slow, like boiling water.

🎬 How JavaScript thinks — step 1 of 11JavaScript is about to run line 12
1function wait(ms) {
2 return new Promise((resolve) => setTimeout(resolve, ms));
3}
4
5async function makeTea() {
6 console.log("Boil water");
7 await wait(500);
8 console.log("Add tea leaves");
9 return "Tea is ready";
10}
11
▶console.log("Start");
13const teaPromise = makeTea();
14console.log("Meanwhile, set the table");
15const message = await teaPromise;
16console.log(message);
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
Start
Boil water
Meanwhile, set the table
Add tea leaves
Tea is ready

💡 Watch the order: "Meanwhile, set the table" prints before "Add tea leaves". Try it: remove the word await on line 7 and run again.

What does an async function return?

An `async` function ALWAYS returns a promise, even if you `return 42`. That is why printing the result directly shows `Promise {…}` and not the number.

To get the real value, `await` the promise. You can also use `.then()` from Lesson 3 — both do the same job.

If the async function throws an error, its promise is "rejected" instead of "fulfilled".

🟨 JavaScript — you can edit this code
Console output
Promise {…}
With await: 87
With then: 87

💡 Try it: change return 87 to return [87, 92, 78] and see what await gives you.

How do I handle errors with async/await in JavaScript?

Put the awaits inside `try { }`. If any awaited promise fails, JavaScript jumps straight to `catch (err)`. The `finally` part runs at the end either way — good for hiding a "Loading…" message.

Careful: `fetch` only fails on its own when there is no network. If the server answers with an error code like 500, fetch still succeeds. So check `res.ok` and throw your own error.

We use the TalentJR practice API here. It has made-up data, and `/broken` always answers with error 500 on purpose.

🟨 JavaScript — you can edit this code
Console output
Loading /quotes/2
Got: { id: 2, text: "Code is like humour: when you have to explain it, it is bad.", topic: "coding" }
Hide the loading spinner
Loading /broken
Problem: Server said 500
Hide the loading spinner

💡 Try it: change "/quotes/2" to "/quotes/99" and see which line catches the problem.

How do I run several awaits at the same time with Promise.all?

Three awaits in a row run one after another: rice (600 ms), then dal (300 ms), then roti (100 ms) — about 1000 ms in total.

`Promise.all([...])` starts all of them together and waits until every one is done — about 600 ms, the time of the slowest. The results come back in the SAME order you listed them, not the order they finished.

Use one-after-another only when a step needs the answer of the step before it.

🎬 How JavaScript thinks — step 1 of 15JavaScript is about to run line 10
1function cook(dish, ms) {
2 return new Promise((resolve) => {
3 setTimeout(() => {
4 console.log(dish, "done");
5 resolve(dish);
6 }, ms);
7 });
8}
9
▶const meal = await Promise.all([
11 cook("Rice", 600),
12 cook("Dal", 300),
13 cook("Roti", 100)
14]);
15console.log("Serve:", meal);
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
Roti done
Dal done
Rice done
Serve: ["Rice", "Dal", "Roti"]

💡 Roti finishes first, but meal is still ["Rice", "Dal", "Roti"]. Try it: write three separate awaits instead and watch the order change.

How do I use await in a loop and show the data on a page?

Use a `for…of` loop when each round must wait for its answer. Do NOT use `forEach` with an async function — forEach does not wait, so the code after it runs too early.

This page loads students 1 to 3 one by one. It shows "Loading…" first and the names as they arrive. Click the button to load them again.

The page stays clickable the whole time. That is the big win of async code: the screen never freezes while you wait.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Loaded Asha
Loaded Rohan
Loaded Meera

💡 Try it: change [1, 2, 3] to [5, 4] and run again.

🤔 Predict the output

Think like JavaScript: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

async function greet() {
  console.log("B");
  await null;
  console.log("D");
}
console.log("A");
greet();
console.log("C");

Question 2. What does this print?

async function getScore() {
  return 42;
}
const x = getScore();
console.log(typeof x);

Question 3. What does this print?

async function check() {
  try {
    await Promise.reject(new Error("No network"));
    console.log("Got data");
  } catch (err) {
    console.log("Caught: " + err.message);
  } finally {
    console.log("Done");
  }
}
await check();

🧩 Your challenge

Weather at the same time: fetch the weather for Pune, Delhi and Shimla TOGETHER using Promise.all and the practice API (`${API}/weather?city=Pune`). Print one line per city, then the hottest city. Expected output looks like: Pune: 24°C Delhi: 14°C Shimla: 4°C Hottest: Pune

Expected output in the console:
Pune: 24°C
Delhi: 14°C
Shimla: 4°C
Hottest: Pune
🟨 JavaScript — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

const API = "https://api.talentjr.in/api/v1/practice";
const res = fetch(`${API}/quotes/1`);
const data = res.json();
console.log(data.text);

TypeError: res.json is not a function

✅ Right

const API = "https://api.talentjr.in/api/v1/practice";
const res = await fetch(`${API}/quotes/1`);
const data = await res.json();
console.log(data.text);

Without await, res is still a Promise, not the response, so it has no .json() method. Put await in front of fetch AND in front of res.json().

❌ Wrong

function loadQuote() {
  const res = await fetch("https://api.talentjr.in/api/v1/practice/quotes/1");
  console.log(res.status);
}
loadQuote();

SyntaxError: Unexpected reserved word

✅ Right

async function loadQuote() {
  const res = await fetch("https://api.talentjr.in/api/v1/practice/quotes/1");
  console.log(res.status);
}
await loadQuote();

await is only allowed inside an async function (or at the top level of a module). Add the word async before function.

❌ Wrong

function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
const homework = ["Maths", "Hindi"];
homework.forEach(async (subject) => {
  await wait(300);
  console.log("Finished", subject);
});
console.log("All homework done!");

No error, but "All homework done!" prints FIRST, before any subject is finished — forEach starts the async functions and moves on without waiting.

✅ Right

function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
const homework = ["Maths", "Hindi"];
for (const subject of homework) {
  await wait(300);
  console.log("Finished", subject);
}
console.log("All homework done!");

forEach does not wait for async functions. A for…of loop with await finishes each round before the next.

📌 Remember

  • An async function always returns a promise; await pauses only that function until the promise is ready.
  • While one function waits, the rest of the page keeps running — nothing freezes.
  • Wrap awaits in try/catch/finally; check res.ok because fetch does not fail on 404 or 500.
  • Promise.all runs several waits together and keeps the results in your order.
  • Use for…of (not forEach) when each loop round must await.

Finished the quiz and the challenge?

Questions students ask

What is the difference between async/await and promises in JavaScript?

They are the same thing underneath. async/await is a cleaner way to write promise code: instead of a chain of .then() calls, you write lines that read top to bottom. You can mix both in one program.

Does await block the whole JavaScript program?

No. await pauses only the async function it is in. Other code, clicks and timers keep running. That is why web pages stay smooth while they load data.

When should I use Promise.all instead of await one by one?

Use Promise.all when the tasks do not depend on each other, like loading weather for three cities. Use one-by-one awaits when step 2 needs the answer of step 1, like getting a student and then that student's marks.

What happens if one promise in Promise.all fails?

Promise.all fails as a whole with that first error, so your catch block runs. If you want every result, even the failed ones, use Promise.allSettled instead.