JavaScript Asynchronous Programming

Detailed explanations & code examples are in the JavaScript (.js) file

Click the { } button at the bottom right to view it

Master Callbacks, Promises, Async/Await, and Fetch API

Topic 38: Synchronous vs Asynchronous

Understanding how JavaScript handles blocking and non-blocking code

⏸️ Synchronous

  • Executes line by line
  • Waits for each operation
  • Blocking (stops execution)
  • Sequential flow

⚡ Asynchronous

  • Multiple operations at once
  • Doesn't wait
  • Non-blocking (continues)
  • Concurrent operations

setTimeout() Function

What is setTimeout()?
Built-in function that executes code after a specified delay

Syntax: setTimeout(callback, milliseconds)
callback - Function to execute after delay
milliseconds - Delay time (1000ms = 1 second)
• Returns timer ID (can cancel with clearTimeout())
ASYNCHRONOUS - doesn't block code execution

Example in Console:

Watch the execution order - Tasks 2, 3, 4 run immediately while Task 1 waits 3 seconds!

Topic 39: Callback Hell

The problem with deeply nested callbacks

⚠️ Callback Hell (Pyramid of Doom):
When callbacks are nested within callbacks, creating hard-to-read code
// This is Callback Hell - hard to read!
task1(() => {
    task2(() => {
        task3(() => {
            task4(() => {
                console.log("Done");
            })
        })
    })
})
Problem Description
Hard to Read Pyramid shape makes code confusing
Difficult to Debug Errors are hard to track down
Messy Error Handling Need separate error handlers for each callback
Hard to Maintain Adding/removing steps is complicated
Solution: Use Promises or async/await (covered in next topics)!

Example in Console:

4 nested tasks that execute sequentially - demonstrates the "pyramid" structure

Topic 40: Promises

Handle asynchronous operations with cleaner syntax

What is a Promise?
A Promise is a JavaScript object used to handle asynchronous tasks.
It tells us whether an operation is pending, successful, or failed.

Promise States

State Description
PENDING Initial state, operation in progress
RESOLVED (fulfilled) Operation completed successfully
REJECTED Operation failed
new Promise((resolve, reject) => {
    if(success){
        resolve("Success!");  // Resolved
    }
    else{
        reject("Failed!");    // Rejected
    }
});

Promise Chaining Rules

Important Rules:
1. .then() waits for Promise before moving foward
2. () => step2() - implicit return (returns promise without having to write return)
3. () => { step2(); } - returns undefined (if in {} return is required)
4. () => { return step2(); } - explicit return (returns promise with having to write return)
5. .catch() catches ANY rejection in the chain

Examples in Console:

Topic 41: Async/Await

Write asynchronous code that looks synchronous

Modern Standard! Async/await is the preferred way to handle async operations
Key Concepts:
async - Makes function return a Promise
await - Pauses function until Promise resolves
• Use try/catch for error handling
• Looks like synchronous code but is asynchronous!
async function fetchData(){
    try {
        const result = await someAsyncOperation();
        console.log(result);
    }
    catch(error) {
        console.error(error);
    }
}
Feature Promises (.then) Async/Await
Syntax Chaining .then() Sequential await
Readability Can get messy ✅ Clean, linear
Error Handling .catch() at end ✅ try/catch blocks
Modern? Still used ✅ Preferred

Examples in Console:

Topic 42: Fetch API

Make HTTP requests to APIs/resources and fetch data

Fetch Basics

What is fetch()?
Function for making HTTP requests to fetch resources

Syntax: fetch(url, {options})
• Returns a Promise
• Used for APIs, images, files, JSON data

Key Methods & Properties

Method/Property Description
response.ok Boolean - true if status 200-299
response.json() Parses JSON - JavaScript object (returns Promise)
response.text() Parses response as plain text
response.blob() Parses as binary data (images, files)

Two Ways to Use Fetch

Method 1: .then()

fetch(url)
    .then(res => res.json())
    .then(data => console.log(data))
    .catch(err => console.error(err));

Method 2: async/await ✅

async function fetchData(){
    const res = await fetch(url);
    const data = await res.json();
}

Live Example:

Fetch real Pokémon data from API! Try both methods:

Why async/await over .then()?
📄 loading...
Loading...