Module 28 // Core JavaScript

Async / Await

Module Objective

Sequential vs parallel async code, try/catch error handling

Mental Model Realtime Simulation

INTERACTIVE_CANVAS
Editor_Pane
Loading...
Console_Output
Waiting for output...

Practical Code Examples

// Example 1
// 1. From Promises to Async/Await
async function getUserData(id) {
  try {
    const user = await fetchUser(id);
    const posts = await fetchPosts(user.id);
    console.log(posts);
  } catch (err) {
    console.log("Error caught:", err);
  }
}

getUserData(1);
💡 The `await` keyword pauses the execution of the async function until the promise is settled. This allows you to write async code that reads top-to-bottom.
// Example 2
// 2. Parallel execution
async function fastFetch() {
  // Start both at once
  const promise1 = fetch('/api1');
  const promise2 = fetch('/api2');

  // Wait for both
  const [res1, res2] = await Promise.all([promise1, promise2]);
}
💡 Don't `await` every line if the tasks are independent! Start the promises first, then `await` them together using `Promise.all`.
// Example 3
// 3. Loops with Async
async function processArray(arr) {
  for (const item of arr) {
    // Sequence: Wait for each one
    await processItem(item);
  }
}
💡 Using `await` inside a `for...of` loop creates a sequence where each iteration waits for the previous one to finish.

Engine & Memory Architecture

Pausing the Context

1. Context Suspension:

  • When the engine hits await, it literally pauses the execution context of that function.
  • The context is moved from the Stack to the Heap.
  • The main thread is freed up to do other work!

2. Resumption:

  • When the promise resolves, the engine pushes a task to the Microtask Queue.
  • When the Event Loop picks it up, the function context is moved back to the Stack and resumes from where it left off.

3. Cost of Pausing:

  • While efficient, pausing and resuming contexts takes a few extra CPU cycles compared to regular callbacks. However, the readability benefit is almost always worth it.