🎉 I'm releasing 12 products in 12 months! If you love product, checkout my new blog workingoutloud.dev

Back to home

Typescript And Promises: Conquering Asynchronous Programming

This post will is 11 of 20 for my series on intermediate-to-advance TypeScript tips.

All tips can be run on the TypeScript Playground.

Introduction

TypeScript, a statically typed superset of JavaScript, has brought a new level of robustness to web development. One of the areas where TypeScript shines is in handling asynchronous programming, particularly with Promises. This blog post will explore how TypeScript and Promises work together to conquer asynchronous programming, providing you with practical examples that you can try out on the TypeScript Playground.

Example 1: Basic Promise

let promise = new Promise<string>((resolve, reject) => { setTimeout(() => { resolve("Promise resolved!"); }, 2000); }); promise.then((value) => { console.log(value); });

This is a basic example of a Promise in TypeScript. A Promise is an object that represents the eventual completion or failure of an asynchronous operation. In this case, we create a new Promise that resolves with a string after 2 seconds. The then method is used to specify what should happen when the Promise is resolved.

Example 2: Promise with Error Handling

let promise = new Promise<string>((resolve, reject) => { setTimeout(() => { reject("Promise rejected!"); }, 2000); }); promise .then((value) => { console.log(value); }) .catch((error: unknown) => { console.error(error); // We can type narrow to handle different error types if (error instanceof Error) { console.log(error.message); // we now know this is of type `Error` with the message property } });

This example is similar to the previous one, but with one key difference: instead of resolving the Promise, we reject it. This simulates an error occurring during the asynchronous operation. We use the catch method to specify what should happen if the Promise is rejected.

In the example, I an also using type narrowing to handle different error types. This is a powerful feature of TypeScript that allows you to write code that is more robust and easier to maintain. See more on type narrowing in my blog post here.

With errors, it is better to set the type to unknown and use narrowing to handle the different types of errors that can occur.

Example 3: Promise Chaining

let promise1 = new Promise<string>((resolve, reject) => { setTimeout(() => { resolve("Promise 1 resolved!"); }, 2000); }); let promise2 = promise1.then((value) => { console.log(value); return "Promise 2 resolved!"; }); promise2.then((value) => { console.log(value); });

This example demonstrates Promise chaining. After the first Promise (promise1) is resolved, its result is passed to the next Promise in the chain (promise2). This allows you to perform multiple asynchronous operations in a specific order.

Example 4: Promise.all

let promise1 = new Promise<string>((resolve, reject) => { setTimeout(() => { resolve("Promise 1 resolved!"); }, 2000); }); let promise2 = new Promise<number>((resolve, reject) => { setTimeout(() => { resolve(2); }, 3000); }); Promise.all([promise1, promise2]).then((values) => { // `values` is type [string, number] console.log(values); });

This example demonstrates the use of Promise.all. This method takes an array of Promises and returns a new Promise that resolves when all of the input Promises have resolved. The result is an array of the values that the input Promises were resolved with.

It understands the return type as provided by the generic, so we can use the values as we would expect (in this case it is [string, number]).

Summary

Promises are a powerful tool for handling asynchronous operations in TypeScript. They allow you to write code that is easier to understand and reason about, especially when dealing with complex asynchronous workflows. Whether you're fetching data from an API, reading a file from disk, or waiting for a timer to finish, Promises can help you manage these operations in a robust and efficient manner.

References

  1. TypeScript Handbook: Promises
  2. MDN Web Docs: Promise
  3. TypeScript Playground

Photo credit: adamj_miller

Personal image

Dennis O'Keeffe

@dennisokeeffe92
  • Melbourne, Australia

Hi, I am a professional Software Engineer. Formerly of Culture Amp, UsabilityHub, Present Company and NightGuru.
I am currently working on Visibuild.

1,200+ PEOPLE ALREADY JOINED ❤️️

Get fresh posts + news direct to your inbox.

No spam. We only send you relevant content.

Typescript And Promises: Conquering Asynchronous Programming

Introduction

Share this post