⚡0 XP🔥0

Asynchronous JavaScript - Promises, async/await and fetch

Lesson 7 of 7 ⏱ 5 min read ✎ 2 exercises ❓ 5-question quiz ▶ Runs HTML, JavaScript

Why JavaScript doesn't wait, the event loop, callbacks, promises, async/await with try/catch, running tasks in parallel with Promise.all, and loading JSON from an API with fetch.

JavaScript doesn't wait#

Loading data from a server, reading a file or waiting for a timer takes time. If JavaScript stopped and waited, the whole page would freeze. Instead it starts the slow task, carries on, and runs your code later when the result is ready. That is asynchronous programming.

▶ Try it YourselfJavaScript
Ctrl + Enter to run
Output
1. Order received
2. Meanwhile, taking the next order
3. Pizza ready (after 1 second)
हिंदी में समझें

सोचिए आप restaurant में order देते हैं। Waiter आपका pizza बनने तक खड़ा नहीं रहता - वह दूसरे customers का order लेता है, और pizza तैयार होने पर लाकर देता है। JavaScript भी यही करती है: धीमा काम शुरू करके आगे बढ़ जाती है, और काम पूरा होने पर बाद में आपका code (callback) चलाती है।

The event loop (in short)#

  1. JavaScript runs your code line by line on one thread (the call stack).
  2. Slow work (timers, network) is handed to the browser.
  3. When it finishes, its callback joins a queue.
  4. When the stack is empty, the event loop takes the next callback from the queue and runs it.

That is why setTimeout(fn, 0) still runs after the current code.

Promises#

Nested callbacks get messy ("callback hell"). A promise is an object that represents a value that will arrive later.

▶ Try it YourselfJavaScript
Ctrl + Enter to run
Output
✓ Seat B2-34 confirmed
✗ No seats available on Shatabdi
Search finished
  • resolve(value) → the promise is fulfilled → .then runs.
  • reject(error) → the promise is rejected → .catch runs.
  • .finally runs either way.

async / await#

async/await lets you write promise code that reads like normal top-to-bottom code.

▶ Try it YourselfJavaScript
Ctrl + Enter to run
Output
Boiling water...
Adding tea leaves...
Tea is ready ☕
Served: chai

An async function always returns a promise. Use try/catch for errors:

async function load() {
  try {
    const data = await getSomething();
    show(data);
  } catch (err) {
    showError(err.message);
  } finally {
    hideSpinner();
  }
}

Running tasks in parallel#

▶ Try it YourselfJavaScript
Ctrl + Enter to run
Output
One by one: 600 ms
[ 'profile', 'courses' ] together: 300 ms

Promise.all fails if any task fails. Promise.allSettled waits for all and tells you which succeeded.

fetch - loading data from an API#

fetch(url) asks a server for data and returns a promise. Most APIs send JSON. This example loads real sample data from the free JSONPlaceholder API (needs internet):

▶ Try it YourselfHTML
Ctrl + Enter to run

Sending data uses the same function with options:

const res = await fetch("/api/enquiry", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "Asha", course: "JavaScript" }),
});
Common Mistake

fetch only rejects when the network fails. A 404 Not Found or 500 still "succeeds" - always check res.ok (or res.status) before using the data.

Summary#

  • Async code starts slow work and continues; callbacks run later via the event loop.
  • A promise is pending → fulfilled (.then) or rejected (.catch).
  • async/await + try/catch is the clearest way to write async code.
  • Promise.all runs independent tasks in parallel.
  • fetch + await res.json() loads data from APIs; check res.ok.
Tip

What next? Combine this with the HTML & CSS course: add a dark-mode toggle, a project filter and a contact form check to your portfolio page. Then move on to React or Node.js in the Full Stack program.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Order tracker

step(name, ms) returns a promise that waits ms milliseconds and then resolves with name. Inside the async function track(), await the three steps in order and print each result as it finishes, then print Delivered!:

Order placed
Packed
Out for delivery
Delivered!
Expected output:
Order placed
Packed
Out for delivery
Delivered!
2

Safe division with try/catch

divide(a, b) returns a promise that rejects with new Error("Cannot divide by zero") when b is 0, otherwise resolves with a / b. Complete run() so it prints Result: 5 for the first call and Error: Cannot divide by zero for the second.

Expected output:
Result: 5
Error: Cannot divide by zero

Quick Quiz

Q1.

What is printed first? setTimeout(() => console.log("A"), 0); console.log("B");

Q2.

A promise can be in which states?

Q3.

Where can you use await?

Q4.

How do you handle errors with async/await?

Q5.

Why use Promise.all([a(), b(), c()])?