Async/Await: Simplifying Asynchronous Code

1. Welcome and Icebreaker:

  • If you could pause and resume any task in your life, what would it be?

2. Outline the Session:

  • We’ll learn about async/await in TypeScript: how to write asynchronous code that looks synchronous.
  • Learning Outcomes: Understand how to use async/await for cleaner async code.
  • Let’s await some results!

3. Concept Explanation:

  • async/await is syntax sugar over Promises, making async code easier to read and write.
  • Use async before a function to make it return a Promise.
  • Use await inside an async function to pause execution until a Promise resolves.
  • Syntax:
    async function getData() {
      const result = await fetchData();
      return result;
    }
    

4. Live Coding Demonstration:

function fetchData(): Promise<string> {
  return new Promise(resolve => {
    setTimeout(() => resolve("Data loaded!"), 1000);
  });
}

async function showData() {
  const data = await fetchData();
  console.log(data);
}

showData();

5. Tasks:

  • Short Exercise:
    1. Write an async function that waits for a Promise to resolve and returns the result.
    2. Use await to call another async function and print the result.
    3. Try using await inside a loop to process multiple async tasks sequentially.