JavaScript Advanced Day 4: Asynchronous Deep Dive

Goal of this Day

Today you will learn:

By the end, you will manage multiple async tasks efficiently.

Step 1: Fetch with async/await

Use async functions with await to get API data:


async function fetchData() {
  try {
    const res = await fetch("https://jsonplaceholder.typicode.com/todos/1");
    const data = await res.json();
    console.log(data);
  } catch(err) {
    console.log("Error:", err);
  }
}

fetchData();

Step 2: Promise.all & Promise.race

Run multiple promises in parallel:


const p1 = fetch("https://jsonplaceholder.typicode.com/todos/1").then(r => r.json());
const p2 = fetch("https://jsonplaceholder.typicode.com/todos/2").then(r => r.json());
const p3 = fetch("https://jsonplaceholder.typicode.com/todos/3").then(r => r.json());

// Wait for all
Promise.all([p1, p2, p3]).then(results => console.log(results));

// Wait for the fastest
Promise.race([p1, p2, p3]).then(result => console.log(result));

Practice


async function fetchData() {
  try {
    const res = await fetch("https://jsonplaceholder.typicode.com/todos/1");
    const data = await res.json();
    console.log(data);
  } catch(err) {
    console.log("Error:", err);
  }
}

fetchData();

Task

Complete the following:

Example:


async function fetchMultiple() {
  const urls = [
    "https://jsonplaceholder.typicode.com/todos/1",
    "https://jsonplaceholder.typicode.com/todos/2",
    "https://jsonplaceholder.typicode.com/todos/3"
  ];
  
  try {
    const promises = urls.map(url => fetch(url).then(r => r.json()));
    const results = await Promise.all(promises);
    console.log(results);
  } catch(err) {
    console.log("Network error:", err);
  }
}

fetchMultiple();