Async / Await

</>Coding Tamilan.← JavaScript course

JavaScript · Lesson 29 / 32 · English

Async / Await

Understand the idea. Change the code. Build confidence with one focused experiment.

Detailed notesRunnable JavaScriptPractice + answer

Read this lesson in தமிழ் ↗.

01 / Understand

Start with the idea

An async function returns a promise. await pauses that function until a promise settles; it does not block the whole JavaScript runtime.

Learning goal: Explain what the example does, predict its result, and change it to solve the practice task.

02 / Explore

Step-by-step lesson notes

Asynchronous JavaScript

JavaScript is single-threaded but handles async operations (network requests, timers, file I/O) using an event loop. Promises and async/await are the modern tools for writing async code.

Promises

JavaScript reference fragmentCODE
// Creating a promise
const fetchData = new Promise((resolve, reject) => {
  setTimeout(() => {
    const success = Math.random() > 0.3;
    if (success) {
      resolve({ data: "Hello!" });
    } else {
      reject(new Error("Network error"));
    }
  }, 1000);
});

// Consuming with .then/.catch
fetchData
  .then(result => console.log(result.data))
  .catch(err => console.error(err.message))
  .finally(() => console.log("Request complete"));

async / await

JavaScript reference fragmentCODE
// async function always returns a Promise
async function getUser(id) {
  try {
    const response = await fetch(`/api/users/${id}`);
    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }
    const user = await response.json();
    return user;
  } catch (err) {
    console.error("Failed to get user:", err.message);
    throw err; // re-throw if needed
  }
}

// Using the async function
const user = await getUser(1);
console.log(user.name);

Promise Combinators

JavaScript reference fragmentCODE
const p1 = fetch("/api/users");
const p2 = fetch("/api/posts");
const p3 = fetch("/api/comments");

// Promise.all — wait for ALL, fail fast on any rejection
const [users, posts, comments] = await Promise.all([p1, p2, p3]);

// Promise.allSettled — wait for ALL, never fails
const results = await Promise.allSettled([p1, p2, p3]);
results.forEach(r => {
  if (r.status === "fulfilled") console.log(r.value);
  else console.error(r.reason);
});

// Promise.race — first one wins (resolved or rejected)
const first = await Promise.race([p1, p2, p3]);

// Promise.any — first RESOLVED wins (ignores rejections)
const fastest = await Promise.any([p1, p2, p3]);

Best practice: Use Promise.allSettled when you want all results regardless of failures. Use Promise.all when all must succeed.

03 / Read & predict

A complete example

Run this complete index.js program in the JavaScript console editor below. The earlier reference fragments may need a browser page or other surrounding setup.

index.js · complete exampleCODE
async function loadProgress() {
  console.log("Loading");
  const lessons = await Promise.resolve(3);
  console.log("Completed: " + lessons);
}
loadProgress().catch(console.error);
console.log("Other work");
Predict first. Reveal the expected result.
Loading
Other work
Completed: 3
04 / Experiment

Make one change. See what happens.

Load the example, change a value, predict the output, and run it again. Use the console output to check your reasoning.

Open editor ↗

Wait for the editor to load, then load this example and press Run.

Powered by the free OneCompiler editor. Code you run is sent to that external service. Keep personal data and secret keys out of your examples.

05 / Your turn

Put the idea to work

Practice challenge

Predict the order if the final log says "Page ready" instead.

Reveal the answer and reasoning

Loading, then Page ready, then Completed: 3. The continuation after await runs asynchronously.

One mistake to avoid: Await a promise inside try/catch when you need to handle its rejection locally. Avoid launching an async task and forgetting its errors.

Your learning checkpoint

  • Explain the example in your own words.
  • Complete the challenge before revealing its answer.
  • Describe the common mistake and how to avoid it.
Coding Tamilan · Learn by doing.