Asynchronous Programming with Promises and Async/Await

Tutorial 3 of 5

Asynchronous Programming with Promises and Async/Await in TypeScript

1. Introduction

Brief explanation of the tutorial's goal

In this tutorial, we will learn about the fundamentals of asynchrony in TypeScript programming. We will focus on Promises and the async/await syntax, powerful tools that allow us to handle time-consuming operations without blocking the execution of our code.

What the user will learn

By the end of this tutorial, you will be able to use Promises and async/await to handle asynchronous operations in TypeScript. You will understand how these techniques can help to keep your code clean and readable, even when dealing with complex asynchronous tasks.

Prerequisites

Familiarity with TypeScript and basic understanding of synchronous vs asynchronous programming is recommended.

2. Step-by-Step Guide

Promises

A Promise in TypeScript is an object representing a value which may not be available yet. It can be in one of three states: pending, fulfilled, or rejected.

let promise = new Promise((resolve, reject) => {
  // do something async
  // on success
  resolve("Success");
  // on failure
  reject("Error");
});

Async/Await

The async/await syntax is syntactic sugar over Promises, making asynchronous code look and behave more like synchronous code.

async function asyncFunc() {
  try {
    let result = await promise; // waits until promise resolves
    console.log(result);
  } catch (error) {
    console.log(error);
  }
}

3. Code Examples

Example 1: Basic Promise

let promise = new Promise<string>((resolve, reject) => {
  setTimeout(() => {
    resolve("Promise fulfilled");
  }, 1000);
});

promise.then(
  value => console.log(value),  // "Promise fulfilled"
  error => console.log(error)
);

This Promise will resolve after 1 second (1000ms), and then print "Promise fulfilled" to the console.

Example 2: Using async/await with Promises

async function asyncFunc() {
  try {
    let result = await promise;
    console.log(result);  // "Promise fulfilled"
  } catch (error) {
    console.log(error);
  }
}

asyncFunc();

This function waits for the Promise to resolve and then prints the result.

4. Summary

We covered the basics of Promises and async/await in TypeScript. These tools make it easier to handle asynchronous operations, providing a way to write non-blocking code in a more readable and manageable way.

5. Practice Exercises

Exercise 1

Write a function that returns a Promise which resolves with the value "Hello, World!" after 2 seconds.

Solution

function helloWorldPromise(): Promise<string> {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve("Hello, World!");
    }, 2000);
  });
}

helloWorldPromise().then(console.log); // "Hello, World!"

Exercise 2

Write an async function that waits for the Promise from Exercise 1 to resolve, and then logs the value to the console.

Solution

async function logHelloWorld() {
  let message = await helloWorldPromise();
  console.log(message); // "Hello, World!"
}

logHelloWorld();

Tips for further practice

Try creating more complex Promises, such as ones that include multiple asynchronous operations. Then, use async/await to handle these Promises in a cleaner and more readable way.