Promises: Handling Asynchronous Operations

1. Welcome and Icebreaker:

  • If you could make any task in your life run in the background and notify you when it’s done, what would it be?

2. Outline the Session:

  • We’ll learn about Promises in TypeScript: how to handle asynchronous operations.
  • Learning Outcomes: Understand how to create, use, and chain Promises for async code.
  • Let’s handle async like a pro!

3. Concept Explanation:

  • Promises represent the eventual completion (or failure) of an asynchronous operation.
  • Use new Promise to create a promise. Use .then, .catch, and .finally to handle results.
  • Promises can be chained for sequential async operations.
  • Syntax:
    const promise = new Promise((resolve, reject) => { ... });
    promise.then(result => { ... }).catch(error => { ... });
    

4. Live Coding Demonstration:

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

fetchData()
  .then(data => console.log(data))
  .catch(err => console.error(err));

// Chaining promises
fetchData()
  .then(data => data.toUpperCase())
  .then(upper => console.log(upper));

5. Tasks:

  • Short Exercise:
    1. Write a function that returns a Promise resolving after 2 seconds.
    2. Chain two .then calls to transform the result.
    3. Write a function that returns a rejected Promise and handle the error with .catch.