Working with Asynchronous APIs

1. Welcome and Icebreaker:

  • If you could fetch any information instantly from anywhere, what would you look up first?

2. Outline the Session:

  • We’ll learn how to work with asynchronous APIs in TypeScript (e.g., fetching data from a server).
  • Learning Outcomes: Understand how to use fetch, Promises, and async/await to interact with APIs.
  • Let’s fetch some data!

3. Concept Explanation:

  • Asynchronous APIs often return Promises (e.g., fetch in browsers).
  • Use await to get results from Promises in async functions.
  • Handle errors with try/catch.
  • Syntax:
    async function getData() {
      const response = await fetch('https://api.example.com/data');
      const data = await response.json();
      return data;
    }
    

4. Live Coding Demonstration:

async function fetchUser() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
    if (!response.ok) throw new Error('Network error');
    const user = await response.json();
    console.log(user);
  } catch (error) {
    console.error('Failed to fetch user:', error);
  }
}

fetchUser();

5. Tasks:

  • Short Exercise:
    1. Write an async function that fetches data from a public API and prints it.
    2. Handle errors if the fetch fails.
    3. Try fetching multiple resources in parallel using Promise.all.