Asynchronous Programming and Integrating Code
Module 7 · Asynchronous Programming and Integrating Code

Asynchronous Programming and Integrating Code

Master callbacks, promises, async/await, and ES modules — the tools that let JavaScript handle slow operations without blocking, and share code across files.

Why Asynchronous Programming?

JavaScript is single-threaded — it can only do one thing at a time. If code blocks waiting for a network response, no other code can run — the browser freezes, the server stops handling requests.

Asynchronous programming solves this: instead of waiting, JavaScript starts a slow operation and continues executing other code. When the slow operation completes, it notifies JavaScript to resume.

The three slow operations that require async:

  • Network requests — fetching data from an API
  • File I/O — reading/writing files (Node.js)
  • Timers — delaying execution

The Event Loop

JavaScript’s concurrency model is built on the event loop:

  1. Run all synchronous code to completion (the “call stack”)
  2. When the stack is empty, check the task queue for pending callbacks
  3. Run the next callback from the queue
  4. Repeat
console.log("1 - start");

setTimeout(() => console.log("3 - timeout"), 0);  // queued, runs after stack clears

console.log("2 - end");

// Output:
// 1 - start
// 2 - end
// 3 - timeout

Even setTimeout(..., 0) defers to the task queue — it never runs before synchronous code finishes.


Callbacks (The Old Way)

The original async pattern: pass a function to be called when the operation completes.

setTimeout(function() {
  console.log("Called after 1 second");
}, 1000);

// Node.js file read:
fs.readFile("data.txt", "utf8", function(error, content) {
  if (error) {
    console.error(error);
    return;
  }
  console.log(content);
});

Callbacks work, but nesting them produces “callback hell”:

// Hard to read and error-prone:
getUser(userId, function(user) {
  getOrders(user.id, function(orders) {
    getOrderDetails(orders[0].id, function(details) {
      processDetails(details, function(result) {
        // ... and so on
      });
    });
  });
});

Promises

A Promise is an object that represents the eventual result of an async operation. It’s either:

  • Pending — the operation is still in progress
  • Fulfilled — completed successfully, with a value
  • Rejected — failed, with a reason (error)
const fetchUser = (id) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (id > 0) {
        resolve({ id, name: "Alice" });  // success
      } else {
        reject(new Error("Invalid ID"));  // failure
      }
    }, 100);
  });
};

fetchUser(1)
  .then(user => console.log(user.name))  // "Alice"
  .catch(error => console.error(error.message));

Promises enable chaining — each .then returns a new promise:

fetch("https://api.example.com/users/1")
  .then(response => response.json())
  .then(user => user.name)
  .then(name => console.log(`Hello, ${name}`))
  .catch(error => console.error("Failed:", error));

async / await

async/await is syntactic sugar over Promises. It makes async code read like synchronous code:

async function getUser(id: number): Promise<{ id: number; name: string }> {
  const response = await fetch(`https://api.example.com/users/${id}`);

  if (!response.ok) {
    throw new Error(`HTTP error: ${response.status}`);
  }

  const user = await response.json();
  return user;
}

// Call an async function:
async function main() {
  try {
    const user = await getUser(1);
    console.log(user.name);
  } catch (error) {
    console.error("Failed to fetch user:", error);
  }
}

await pauses execution of the async function until the Promise resolves. Other code can still run while it waits — the thread isn’t blocked.

💻 Code Lab: Running Async Operations in Parallel

await in a loop runs operations sequentially — each waits for the previous:

// Sequential — total time is sum of all delays:
for (const id of userIds) {
  const user = await getUser(id);  // waits for each
  process(user);
}

// Parallel — total time is the longest single delay:
const users = await Promise.all(
  userIds.map(id => getUser(id))  // all start at once
);
users.forEach(process);

Use Promise.all when operations are independent. Use sequential await when each operation depends on the result of the previous one.

// Promise.allSettled — doesn't fail fast if one rejects:
const results = await Promise.allSettled(
  userIds.map(id => getUser(id))
);
results.forEach(result => {
  if (result.status === "fulfilled") {
    process(result.value);
  } else {
    console.error("Failed:", result.reason);
  }
});

ES Modules

Modules let you split code across files and explicitly declare what each file exports and imports. This replaces the old <script> tag soup and makes dependencies clear.

Exporting:

// math.ts
export function add(a: number, b: number): number {
  return a + b;
}

export function multiply(a: number, b: number): number {
  return a * b;
}

export const PI = 3.14159;

// Default export — one per file:
export default function divide(a: number, b: number): number {
  return a / b;
}

Importing:

// main.ts
import divide from "./math";          // default import
import { add, multiply, PI } from "./math";  // named imports
import * as math from "./math";        // namespace import

console.log(add(2, 3));        // 5
console.log(math.multiply(4, 5)); // 20
console.log(PI);               // 3.14159

Generators

A generator function can pause and resume execution. It returns an iterator that you can advance step by step with next():

function* count(start: number, end: number): Generator<number> {
  for (let i = start; i <= end; i++) {
    yield i;  // pauses here, returns i to the caller
  }
}

const counter = count(1, 5);
counter.next()  // { value: 1, done: false }
counter.next()  // { value: 2, done: false }
counter.next()  // { value: 3, done: false }

// Use in a for...of loop:
for (const n of count(1, 5)) {
  console.log(n);  // 1, 2, 3, 4, 5
}

Generators are useful for representing sequences that are expensive to compute all at once (lazy evaluation), implementing infinite sequences, and writing async iterators.

⚠️ Common Pitfall: Unhandled Promise Rejections

A Promise that rejects with no .catch handler (or try/catch in async/await) is an unhandled rejection. In Node.js 15+, this crashes the process. In browsers, it logs a console error.

// Bad — rejection is silently ignored:
async function badFetch() {
  const data = await fetch("/api/data");  // might reject — no try/catch!
  return data.json();
}

// Good — always handle rejections:
async function goodFetch() {
  try {
    const response = await fetch("/api/data");
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return await response.json();
  } catch (error) {
    console.error("Fetch failed:", error);
    throw error;  // re-throw so callers know it failed
  }
}

Make it a habit: every async function that can fail should have a try/catch.


🧠 Knowledge Check

What is the difference between Promise.all and Promise.allSettled?

Reveal Answer & Explanation

Promise.all resolves when all promises fulfill — but rejects immediately (“fails fast”) if any promise rejects. If you have 10 promises and one rejects, Promise.all rejects and you don’t get the results of the other 9.

Promise.allSettled waits for all promises to either fulfill or reject — it never rejects. It returns an array of result objects, each with a status of "fulfilled" (with value) or "rejected" (with reason). Use this when you need all results regardless of individual failures — for example, fetching from multiple APIs where partial success is acceptable.


What’s Next

You now understand JavaScript’s async model — the event loop, Promises, async/await, and generators — along with how to organize code with ES modules. In Module 8, we’ll shift into computer science theory: searching and sorting algorithms, including how to analyze their efficiency with Big O notation.