JS 16

 Great choice. Chapter 16 (Async/Await) is one of the most valuable chapters in modern JavaScript. If you master this, you'll be able to work with APIs, React, Node.js, databases, and almost every real-world application.

Assumption: Since you skipped to Chapter 16, I assume you already understand Promises (.then() and .catch()) from Chapter 15.


Chapter 16 — Async/Await

🎯 Goal (1 line)

Write asynchronous code that looks like normal step-by-step code.


2-Minute Lesson

Imagine you've ordered pizza.

Synchronous code

You stand outside the restaurant until the pizza is ready.

Only then do you go home.

Order Pizza
↓
Wait...
↓
Get Pizza
↓
Go Home

Asynchronous code

You order the pizza.

Go shopping.

Come back when it's ready.

Order Pizza
↓
Go Shopping
↓
Pizza Ready
↓
Pick It Up

JavaScript uses asynchronous programming because waiting would freeze the webpage.


Promise (old style)

fetch("/users")
  .then(response => response.json())
  .then(data => console.log(data));

Async/Await (modern style)

async function getUsers() {
  const response = await fetch("/users");
  const data = await response.json();

  console.log(data);
}

Much easier to read.


New Syntax

async

Marks a function as asynchronous.

async function hello() {}

or

const hello = async () => {};

await

Pause only this async function until the Promise finishes.

const data = await fetch(url);

await can only be used inside an async function.


MCQ 1

Which keyword makes a function asynchronous?

A. await

B. async

C. promise

D. then


✅ Answer

B

async tells JavaScript that this function works with asynchronous operations.


MCQ 2

Where can you use await?

A. Anywhere

B. Only inside an async function

C. Only inside loops

D. Only inside objects


✅ Answer

B

Using await outside an async function causes an error (unless you're using top-level await in modules, which we'll ignore for now).


MCQ 3

Predict the output.

async function test() {
  console.log("Hello");
}

test();

A.

Hello

B.

undefined

C. Error

D. Nothing


✅ Answer

A

Calling the async function executes it, and "Hello" is printed.


MCQ 4

Find the bug.

function getData() {
  const data = await fetch("/users");
}

A. No bug

B. Missing async

C. Missing return

D. Missing const


✅ Answer

B

Correct:

async function getData() {
  const data = await fetch("/users");
}

MCQ 5

Which is easier to read?

A.

fetch(url)
  .then(res => res.json())
  .then(data => console.log(data));

B.

const res = await fetch(url);
const data = await res.json();

console.log(data);

✅ Answer

B

This is why async/await became the preferred style.


MCQ 6

Predict the output.

async function hello() {
  return "Hi";
}

hello().then(console.log);

A.

Hi

B.

undefined

C. Error

D. Promise


✅ Answer

A

An async function always returns a Promise.

That Promise resolves with "Hi".


MCQ 7

What does an async function always return?

A. Number

B. Object

C. Promise

D. String


✅ Answer

C

Even this:

async function test() {
  return 10;
}

actually returns:

Promise → 10

MCQ 8

Predict the output.

async function test() {
  return 5;
}

console.log(test());

A.

5

B.

Promise { ... }

C.

undefined

D. Error


✅ Answer

B

Remember:

async always returns a Promise.


MCQ 9

Find the bug.

async function getUsers() {
  const response = fetch("/users");

  const data = response.json();

  console.log(data);
}

A. No bug

B. Missing await

C. Missing let

D. fetch should use const


✅ Answer

B

Correct:

const response = await fetch("/users");
const data = await response.json();

MCQ 10

Which waits for the fetch to finish?

A.

fetch(url);

B.

await fetch(url);

C.

async fetch(url);

D.

fetch.await(url);

✅ Answer

B

await pauses until the Promise resolves.


MCQ 11

Predict the output.

async function demo() {
  console.log(1);

  await Promise.resolve();

  console.log(2);
}

demo();

console.log(3);

A.

1
2
3

B.

1
3
2

C.

3
1
2

D.

2
1
3

✅ Answer

B

Execution:

  • Print 1

  • Pause at await

  • Continue outside

  • Print 3

  • Resume async function

  • Print 2


MCQ 12

How do you catch errors?

A.

if(error)

B.

try...catch

C.

error.catch()

D.

await.catch()

✅ Answer

B


MCQ 13

Predict the output.

async function test() {
  try {
    throw new Error("Oops");
  } catch {
    console.log("Caught");
  }
}

test();

A.

Caught

B.

Oops

C. Error

D. Nothing


✅ Answer

A

The error is handled inside catch.


MCQ 14

Which is better?

A.

fetch(url)
.then(...)
.then(...)
.then(...)
.then(...)

B.

async function load() {
  const res = await fetch(url);
  const data = await res.json();
}

✅ Answer

B

It's flatter, easier to read, and easier to debug.


MCQ 15

Predict the output.

async function test() {
  return await Promise.resolve(20);
}

test().then(console.log);

A.

20

B.

Promise

C.

undefined

D. Error


✅ Answer

A

The Promise resolves to 20.


MCQ 16

Which runs one after another?

const a = await fetch("/a");
const b = await fetch("/b");

A. Sequential

B. Parallel

C. Random

D. None


✅ Answer

A

The second fetch starts only after the first finishes.


MCQ 17

Which runs both requests at the same time?

A.

await fetch("/a");
await fetch("/b");

B.

const a = fetch("/a");
const b = fetch("/b");

await Promise.all([a, b]);

C.

fetch("/a").fetch("/b");

D.

await fetch.all();

✅ Answer

B

Promise.all() runs multiple asynchronous tasks in parallel.


MCQ 18 (Hard)

Predict the output.

async function test() {
  console.log("A");

  await Promise.resolve();

  console.log("B");
}

console.log("C");

test();

console.log("D");

A.

A
B
C
D

B.

C
A
D
B

C.

A
C
D
B

D.

C
D
A
B

✅ Answer

B

Step by step:

console.log("C") → C

test()

console.log("A") → A

await → pause

console.log("D") → D

resume

console.log("B") → B

Final output:

C
A
D
B

Common Beginner Mistakes

❌ Forgetting to add async before using await.

❌ Forgetting to await fetch() or response.json().

❌ Thinking await freezes the whole program—it only pauses the current async function.

❌ Forgetting that an async function always returns a Promise.

❌ Running independent async tasks sequentially when Promise.all() would be faster.


Mini Coding Challenge

Question

Predict the output.

async function greet() {
  console.log("Hello");

  await Promise.resolve();

  console.log("World");

  return "Done";
}

greet().then(console.log);

console.log("JavaScript");

Take a moment before looking at the answer.


✅ Answer

Output:

Hello
JavaScript
World
Done

Why?

  1. greet() starts and prints Hello.

  2. It reaches await and pauses.

  3. The next line outside the function runs: JavaScript.

  4. The async function resumes and prints World.

  5. The Promise returned by greet() resolves with "Done", so .then(console.log) prints Done.


Mini Project — Fake User Loader

Problem

Create a function that simulates loading a user after 2 seconds.

Solution

function fetchUser() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({
        name: "Alice",
        age: 25
      });
    }, 2000);
  });
}

async function loadUser() {
  console.log("Loading...");

  const user = await fetchUser();

  console.log(user);

  console.log("Finished!");
}

loadUser();

Expected Output (after ~2 seconds)

Loading...

{ name: "Alice", age: 25 }

Finished!

🎯 Chapter 16 Takeaways (The 20% That Gives You 80%)

  1. Mark asynchronous functions with async.

  2. Use await to pause until a Promise resolves.

  3. await works only inside an async function.

  4. Every async function returns a Promise.

  5. Use try...catch for error handling with async/await.

  6. Use Promise.all() when independent asynchronous tasks can run in parallel.

  7. Most API calls in React and Node.js are written with async/await.

These patterns are used daily in frontend and backend development and are among the most common topics in JavaScript interviews.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.