Promise Class in TypeScript

Promise Class in TypeScript

This article explains the Promise class in TypeScript.

YouTube Video

Promise

The Promise class in TypeScript is basically the same as Promise in JavaScript. A Promise is a built-in class for handling asynchronous operations, representing the result of an asynchronous operation when it completes. Here, we explain the basic usage of Promises and related concepts.

Basic Usage

Creating a Promise:

A Promise object is used to wrap asynchronous operations. A Promise is created with new Promise(executor), and it executes asynchronous operations inside it. The executor takes two functions, resolve and reject, as arguments.

1const myPromise = new Promise<number>((resolve, reject) => {
2    // Perform asynchronous operations
3    const success = true; // This is just an example
4    if (success) {
5        resolve(42); // In case of success
6    } else {
7        reject('Failed'); // In case of failure
8    }
9});

Using a Promise:

The created Promise is processed using then() and catch().

1myPromise.then((value) => {
2    console.log(`Success: ${value}`); // Process the value passed with resolve
3}).catch((error) => {
4    console.error(`Error: ${error}`); // Handle the error passed with reject
5});

finally() method

 1const myPromise = new Promise<number>((resolve, reject) => {
 2    // Perform asynchronous operations
 3    const success = false; // This is just an example
 4    if (success) {
 5        resolve(42); // In case of success
 6    } else {
 7        reject('Failed'); // In case of failure
 8    }
 9});
10
11myPromise.then((value) => {
12    console.log(`Success: ${value}`); // Process the value passed with resolve
13}).catch((error) => {
14    console.error(`Error: ${error}`); // Handle the error passed with reject
15}).finally(() => {
16    console.log('The operation has completed');
17});
  • The finally() method defines code that will always be executed regardless of whether the Promise is fulfilled or rejected.

Chaining Promises:

By chaining then() after then(), you can connect multiple asynchronous operations in series.

 1const myPromise = new Promise<number>((resolve, reject) => {
 2    // Perform asynchronous operations
 3    const success = true; // This is just an example
 4    if (success) {
 5        resolve(42); // In case of success
 6    } else {
 7        reject('Failed'); // In case of failure
 8    }
 9});
10
11myPromise
12    .then((value) => {
13        console.log(`Success: ${value}`);
14        return value + 1; // Pass the value to the next then
15    })
16    .then((newValue) => {
17        console.log(`New value: ${newValue}`);
18    })
19    .catch((error) => {
20        console.error(`Error: ${error}`);
21    });

async/await:

In TypeScript, you can handle Promises more straightforwardly using async/await. Within an async function, you can use the await keyword to wait for the result of a Promise.

 1const myPromise = new Promise<number>((resolve, reject) => {
 2    // Perform asynchronous operations
 3    const success = true; // This is just an example
 4    if (success) {
 5        resolve(42); // In case of success
 6    } else {
 7        reject('Failed'); // In case of failure
 8    }
 9});
10
11async function asyncFunction() {
12    try {
13        const value = await myPromise;
14        console.log(`Success: ${value}`);
15    } catch (error) {
16        console.error(`Error: ${error}`);
17    }
18}
19
20asyncFunction();

Promise Methods

Promise.all()

Promise.all executes multiple Promises concurrently and waits until all of them are fulfilled.

 1const promise1 = Promise.resolve(1);
 2const promise2 = Promise.resolve(2);
 3const promise3 = Promise.resolve(3);
 4
 5Promise.all([promise1, promise2, promise3])
 6    .then((results) => {
 7        console.log(results);  // [1, 2, 3]
 8    })
 9    .catch((error) => {
10        console.error('Error :', error);
11    });
  • then() is called only when all Promises are fulfilled. catch() is called if even one fails.

Promise.race()

Promise.race returns the result of the first Promise that completes among multiple Promises.

1const promise1 = new Promise((resolve) => setTimeout(resolve, 100, 'First'));
2const promise2 = new Promise((resolve) => setTimeout(resolve, 500, 'Second'));
3
4Promise.race([promise1, promise2]).then((result) => {
5    console.log(result);  // "First"
6});
  • As in this example, the result of the first Promise that completes is returned.

Promise.allSettled()

Promise.allSettled waits for all Promises to complete and returns an array of all results, including both fulfilled and rejected.

 1const promise1 = Promise.resolve(1);
 2const promise2 = Promise.reject("Failed");
 3const promise3 = Promise.resolve(3);
 4
 5Promise.allSettled([promise1, promise2, promise3])
 6    .then((results) => {
 7        results.forEach(result => console.log(result));
 8        // [
 9        //   { status: 'fulfilled', value: 1 },
10        //   { status: 'rejected', reason: 'Failed' },
11        //   { status: 'fulfilled', value: 3 }
12        // ]
13    });
  • then() is called once all Promises have completed (either fulfilled or rejected). Each result includes a status property ('fulfilled' or 'rejected'). Failures do not affect the other operations.

Promise.any()

Promise.any waits until the first Promise is fulfilled and returns it.

 1const promise1 = new Promise((resolve) => setTimeout(() => resolve("A ok"), 300));
 2const promise2 = new Promise((_, reject) => setTimeout(() => reject("B fail"), 100));
 3const promise3 = new Promise((resolve) => setTimeout(() => resolve("C ok"), 200));
 4
 5Promise.any([promise1, promise2, promise3])
 6    .then(value => {
 7        // Logs the first fulfilled value ("C ok")
 8        console.log("first fulfilled:", value);
 9    })
10    .catch(err => {
11        console.log("should not reach here in this example:", err);
12    });
  • It returns the first fulfilled value among multiple Promises.

Summary

By using TypeScript, you can specify the types of Promises appropriately, allowing you to write more type-safe programs. This helps in catching errors early during development by specifying the type of value that a Promise returns in advance.

You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.

YouTube Video