Implement Promise in TypeScript


Objectives

Exploring common use cases of Promises in TypeScript

How Promise works

Basic Promise

Handling asynchronous operations

Let's walk through the code:

  • The fetchData function returns a Promise that resolves to a string.
  • Inside the fetchData function, a new Promise is created using the Promise constructor and a setTimeout function is used to simulate an asynchronous operation.
  • If the data exists, the Promise is fulfilled by calling resolve(data). Otherwise, the Promise is rejected by calling reject("Data not found").
  • The fetchData function is called, and the returned Promise is chained with a then method to handle the resolved value.
  • Inside the then method, a callback function logs a message and the received data to the console.
  • The Promise chain also includes a catch method to handle any errors, with a callback function that logs an error message to the console.

Chaining Promises

Let's walk through the code:

  • The code defines two functions: fetchUser and fetchUserPosts.
  • The fetchUser function takes a userId as a parameter and returns a promise that resolves with a string representing the user's name ("Sung-Jie Hung") if the userId is 1, or rejects with an error message ("User not found") otherwise. This function simulates an asynchronous operation using setTimeout.
  • The fetchUserPosts function takes a user string as a parameter and returns a promise that resolves with an array of strings representing the user's posts ("Post 1", "Post 2", "Post 3"). This function also simulates an asynchronous operation using setTimeout.
  • The code then uses these two functions to fetch a user with userId 1 and log the user's name and posts.
  • It does this by calling fetchUser(1), which returns a promise. When that promise resolves successfully, the then block is executed, which logs the user's name and then calls fetchUserPosts(user), passing the user's name as an argument.
  • The fetchUserPosts promise is also handled with a then block, which logs the user's posts.
  • If any error occurs during the promise chain, the catch block is executed, which logs the error message.

Using Promise.all()

Let's walk through the code:

  • The code uses Promise.all to concurrently execute three promises: fetchUser, fetchUserPosts, and fetchUserComments. It passes an array of promises as an argument to Promise.all.
  • If all promises are resolved successfully, the then callback is executed, receiving an array containing the resolved values of the promises: [user, posts, comments].
  • Inside the then callback, it logs the user, user posts, and user comments to the console.
  • If any of the promises is rejected, the catch callback is executed, logging the error to the console.

Source