JavaScript + Node.js track

Lesson 16 · Part 4: Async

async/await

`async` functions, `try/catch` and parallel vs sequential execution

Part 4: Async2 min readFree lesson

Level: Intermediate | Player: 15_Promise

Learning Objectives

  • We know that the async function always returns Promise.
  • With await, the Promise value can be received synchronously.
  • Handle asynchronous errors with try/catch.
  • Know the difference between parallel execution and sequential execution.
  • Processes efficiently by combining Promise.all and await.

1. async function

For functions with the async keyword, the return value is automatically wrapped in a Promise.

async function f() {
  return 42;
}
f().then((v) => console.log(v)); // 42

2. await

await pauses function execution until the Promise is determined. async Can only be used inside functions (excluding top-level modules).

async function main() {
  const value = await Promise.resolve(10);
  console.log(value); // 10
}

3. try / catch

Asynchronous errors are caught with try/catch.

async function load() {
  try {
    const data = await fetchData();
    console.log(data);
  } catch (err) {
    console.error(err);
  }
}

4. Parallel vs sequential

Successive await operations are slow because the next operation begins only after the previous operation has finished. Parallelize independent tasks with Promise.all.

//Slow (sequential)
const a = await fetchA();
const b = await fetchB();

//Fast (parallel)
const [a, b] = await Promise.all([fetchA(), fetchB()]);

Core example

file Contents covered
01_async_basic.js async functions and await basics
02_try_catch.js Error handling with try/catch
03_promise_all.js await + Promise.all
04_parallel.js Parallel vs sequential time comparison

⚠️ Common Mistakes

  1. Using await in a function other than async → SyntaxError.
  2. Waste time by writing independent tasks as consecutive await.
  3. Unhandled rejection by awaiting without try/catch.
  4. forEach((x) => await ...) does not work (callback is not async).
  5. Use the return value of the async function as is without resolving it with then.

❓ Frequently Asked Questions (FAQ)

Q1. Can await be used at the top level of a module? A. It is possible in top-level await (ESM only) in ES2022.

Q2. What if an async function throws? A. The returned Promise is in a rejected state.

Q3. Which is better: await or .then? A. Readability is usually better with await. branch/combination When simple, .then is sufficient.

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

src/01_async_basic.jsJavaScript
/**
 *Default behavior of async functions and await.
 */
function delay(ms, value) {
  return new Promise((resolve) => setTimeout(() => resolve(value), ms));
}

async function main() {
  console.log("start");
  const value = await delay(200, "Hello!");
  console.log("Received:", value);
  console.log("end");
}

main();
src/02_try_catch.jsJavaScript
/**
 *Handle asynchronous errors with try/catch.
 */
function fetchData(ok) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (ok) resolve({ id: 1 });
      else reject(new Error("network failure"));
    }, 100);
  });
}

async function run() {
  try {
    const data = await fetchData(false);
    console.log("Success:", data);
  } catch (err) {
    console.error("Error:", err.message);
  } finally {
    console.log("organizing");
  }
}

run();
src/03_promise_all.jsJavaScript
/**
 *Combine await and Promise.all to receive parallel results.
 */
function fetchValue(label, ms) {
  return new Promise((resolve) => setTimeout(() => resolve(label), ms));
}

async function loadAll() {
  const [a, b, c] = await Promise.all([
    fetchValue("A", 100),
    fetchValue("B", 200),
    fetchValue("C", 150),
  ]);
  console.log("All values:", a, b, c);
}

loadAll();
src/04_parallel.jsJavaScript
/**
 *Compare the execution time of sequential await and parallel await(Promise.all).
 */
function work(label, ms) {
  return new Promise((resolve) => setTimeout(() => resolve(label), ms));
}

async function sequential() {
  const start = Date.now();
  await work("A", 200);
  await work("B", 200);
  await work("C", 200);
  console.log("Sequence:", Date.now() - start, "ms");
}

async function parallel() {
  const start = Date.now();
  await Promise.all([work("A", 200), work("B", 200), work("C", 200)]);
  console.log("Parallel:", Date.now() - start, "ms");
}

(async () => {
  await sequential();
  await parallel();
})();

Assignment

1. User + Post

Create fake fetchUser(id) and fetchPosts(userId) and call them one by one in the async function to print the results.

2. Parallel requests

Start fake requests corresponding to three URLs simultaneously with Promise.all and measure the time.

The reference solution is shown below.

Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

homework_01.jsJavaScript
/**
 *After importing a user, fetch that user's posts.
 */
function fetchUser(id) {
  return new Promise((resolve) => {
    setTimeout(() => resolve({ id, name: "Jimin" }), 100);
  });
}

function fetchPosts(userId) {
  return new Promise((resolve) => {
    setTimeout(() => resolve([{ id: 1, userId, title: "first post" }]), 100);
  });
}

async function main() {
  try {
    const user = await fetchUser(1);
    const posts = await fetchPosts(user.id);
    console.log(user.name, "Post by:", posts);
  } catch (err) {
    console.error(err);
  }
}

main();
homework_02.jsJavaScript
/**
 *Send fake requests from three URLs in parallel and measure the total time.
 */
function fakeFetch(url, ms) {
  return new Promise((resolve) => setTimeout(() => resolve(`${url} OK`), ms));
}

async function main() {
  const start = Date.now();
  const results = await Promise.all([
    fakeFetch("/a", 200),
    fakeFetch("/b", 250),
    fakeFetch("/c", 150),
  ]);
  console.log("Result:", results);
  console.log("Total Time:", Date.now() - start, "ms");
}

main();

Learn this lesson with a mentor

Work through the JavaScript + Node.js track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now