TalentJR

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

Async & Promises – How JavaScript Waits Without Freezing

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

In this lesson you will

  • Predict the order in which synchronous code, timers and Promises run
  • Create a Promise and handle its result with then, catch and finally
  • Use async/await and Promise.all to write waiting code that reads top to bottom

You order chai at the school canteen. The canteen uncle does not freeze until your chai is ready — he takes the next order, and calls your name when it is done. JavaScript works the same way with slow jobs like timers and downloads. A Promise is your token number: a promise that the result will come later.

What does asynchronous mean in JavaScript?

Normal code is synchronous: line 1, then line 2, then line 3. Each line finishes before the next starts.

Some jobs take time, like a timer or loading data from the internet. If JavaScript waited for them, the whole page would freeze. So it starts the slow job, moves on, and comes back when the job is done. That is asynchronous code.

In Class 8 Lesson 14 you used `setTimeout`. Even with a delay of 0 ms, its function runs only after all the normal code has finished.

🎬 How JavaScript thinks — step 1 of 5JavaScript is about to run line 1
▶console.log("1. Order chai");
2setTimeout(() => {
3 console.log("3. Chai is ready!");
4}, 0);
5console.log("2. Take the next order");
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
1. Order chai
2. Take the next order
3. Chai is ready!

💡 Try it: change 0 to 1000. The order of the lines stays the same — only the wait changes.

What is a callback, and why do people say callback hell?

A callback is a function you hand to another function, saying "call this when you are done". The timer above used one.

Callbacks work, but when one slow step must wait for another, they nest inside each other. The code drifts to the right and gets hard to read. People call this callback hell.

Look at three steps of making a tiffin. Each step sits inside the one before it.

🟨 JavaScript — you can edit this code
Console output
Done: boil potatoes
Done: make sabzi
Done: pack tiffin
Tiffin ready! 🍱

💡 Imagine ten steps instead of three. Promises were invented to flatten this staircase.

What is a Promise in JavaScript?

A Promise is an object that stands for a result that is not ready yet. It is in one of three states: pending (waiting), fulfilled (worked) or rejected (failed).

You make one with `new Promise((resolve, reject) => { ... })`. Call `resolve(value)` when the job works, or `reject(error)` when it fails.

`.then(fn)` runs `fn` with the value once the Promise is fulfilled. Each `.then` returns a new Promise, so you can chain them in a flat line instead of nesting.

🟨 JavaScript — you can edit this code
Console output
Done: boil potatoes
Done: make sabzi
Done: pack tiffin 🍱

💡 Same three steps as before, but no staircase. Returning a Promise from then makes the next then wait for it.

How do I handle a failed Promise with catch and finally?

Things go wrong: the canteen runs out of milk. Then the Promise calls `reject` with an Error.

`.catch(fn)` runs only when something in the chain failed. `.finally(fn)` runs at the end either way — good for clean-up like "close the counter".

Without a catch, a rejected Promise shows a red error in the console. Always handle failure.

🟨 JavaScript — you can edit this code
Console output
Sorry: No milk left
Next customer, please!

💡 Try it: change makeChai(0) to makeChai(2) and run again.

How do async and await make Promises easier in JavaScript?

`await` pauses an `async` function until a Promise settles, and gives you its value. The rest of the page keeps running meanwhile.

The code now reads top to bottom, like a recipe. For failures, wrap it in `try { } catch { }` (more in Lesson 5).

`await` only works inside a function marked `async` — or at the top level of a module, like these lesson boxes.

🎬 How JavaScript thinks — step 1 of 11JavaScript is about to run line 12
1function wait(ms, value) {
2 return new Promise((resolve) => setTimeout(() => resolve(value), ms));
3}
4async function morning() {
5 console.log("Alarm rings ⏰");
6 const bath = await wait(300, "bath done");
7 console.log(bath);
8 const food = await wait(200, "breakfast done");
9 console.log(food);
10 return "Off to school!";
11}
▶const result = await morning();
13console.log(result);
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
Alarm rings ⏰
bath done
breakfast done
Off to school!

💡 An async function always returns a Promise. That is why we await morning() to get its text.

How do I wait for many Promises at once with Promise.all?

Waiting one by one is slow when the jobs do not depend on each other. Three friends can buy samosa, chai and juice at the same time.

`Promise.all([...])` starts waiting on all of them together. It gives back an array of results, in the same order you passed them in — not the order they finished.

If any one fails, `Promise.all` fails too. The total wait is about the slowest job, not the sum.

🟨 JavaScript — you can edit this code
Console output
got chai
got juice
got samosa
["samosa", "chai", "juice"]

💡 The "got" lines come in finishing order; the array keeps the order you asked for.

🤔 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?

console.log("A");
setTimeout(() => console.log("B"), 0);
console.log("C");

Question 2. What does this print?

Promise.resolve(5)
  .then((x) => x * 2)
  .then((x) => console.log(x));

Question 3. What does this print?

console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");

🧩 Your challenge

Make a train-ticket booking with Promises. Write checkSeats(seats) that returns a Promise: after 300 ms it resolves with "Seat confirmed" if seats > 0, else rejects with new Error("Waiting list"). Then write an async function book(name, seats) that awaits checkSeats and prints the result, using try/catch to print failures. Book Aarav (5 seats left) and then Diya (0 seats left). Expected output: Aarav: Seat confirmed ✅ Diya: Waiting list ❌

Expected output in the console:
Aarav: Seat confirmed ✅
Diya: Waiting list ❌
🟨 JavaScript — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

function getScore() {
  setTimeout(() => {
    return 42;
  }, 300);
}
console.log("Score:", getScore());

No error, but it prints "Score: undefined" — getScore has already finished before the timer fires.

✅ Right

function getScore() {
  return new Promise((resolve) => {
    setTimeout(() => resolve(42), 300);
  });
}
console.log("Score:", await getScore());

The return inside the timer only returns from the little arrow function, much later. getScore itself returns nothing. Return a Promise and await it.

❌ Wrong

async function loadStudent() {
  return { name: "Meera", cls: 9 };
}
const student = loadStudent();
console.log(student.name.toUpperCase());

TypeError: Cannot read properties of undefined (reading 'toUpperCase')

✅ Right

async function loadStudent() {
  return { name: "Meera", cls: 9 };
}
const student = await loadStudent();
console.log(student.name.toUpperCase());

An async function returns a Promise, not the object. Without await, student is the Promise, and student.name is undefined.

❌ Wrong

function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
function countdown() {
  console.log("3");
  await wait(300);
  console.log("Go!");
}
countdown();

SyntaxError: Unexpected reserved word

✅ Right

function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
async function countdown() {
  console.log("3");
  await wait(300);
  console.log("Go!");
}
countdown();

await is only allowed inside a function marked async (or at the module's top level). Add async before function.

📌 Remember

  • Asynchronous code starts a slow job, moves on, and handles the result later.
  • Timer callbacks run only after all normal code has finished — even with 0 ms.
  • A Promise is pending, then fulfilled (resolve) or rejected (reject).
  • then handles the value, catch handles failure, finally runs either way.
  • await pauses an async function until a Promise settles; use try/catch for failures.
  • Promise.all waits for many Promises together and keeps the results in order.

Finished the quiz and the challenge?

Questions students ask

Is JavaScript single-threaded? Then how does it do two things at once?

JavaScript runs your code on one thread, one line at a time. Slow jobs like timers and downloads are handled by the browser in the background. When one finishes, its callback waits in a queue and runs once your current code is done.

What is the difference between a callback and a Promise?

A callback is a function you pass in to be called later. A Promise is an object that represents the future result, which you can pass around and chain with then. Promises avoid deep nesting and make error handling easier.

Should I use then or async/await?

Both work with the same Promises. async/await usually reads more easily, so most modern code uses it. You still need to understand then, because you will see it in a lot of code.

Why does setTimeout with 0 ms not run straight away?

0 ms only means "as soon as possible". The callback is put in a queue, and the queue is checked only after the current code finishes. So it always runs after the lines below it.