Skip to main content

Promises in TypeScript (Live Playground)

In this tutorial, we will explore Promises in TypeScript, which provide a more structured and readable way to handle asynchronous tasks, avoiding the callback hell issue.

What are Promises?

A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. A Promise is said to be in one of three states:

  1. Pending: The initial state; neither fulfilled nor rejected.
  2. Fulfilled: The operation completed successfully, and the Promise has a resulting value.
  3. Rejected: The operation failed, and the Promise has a reason for the failure.

Creating Promises

To create a Promise, you can use the Promise constructor, which takes a single argument: a function called the "executor." The executor takes two arguments: a resolve function and a reject function.

TypeScript
const myPromise = new Promise<string>((resolve, reject) => {
// Asynchronous operation
});

The resolve function is used to fulfill the Promise with a value, while the reject function is used to reject the Promise with a reason.

TypeScript
const myPromise = new Promise<string>((resolve, reject) => {
setTimeout(() => {
resolve('Promise resolved!');
}, 1000);
});

Handling Promise Results

To handle the results of a Promise, you can use the then method for fulfilled Promises and the catch method for rejected Promises. You can also use the finally method to execute a function when the Promise is settled, regardless of its outcome.

TypeScript
myPromise
.then(value => {
console.log(value); // Output: Promise resolved!
})
.catch(reason => {
console.error(reason);
})
.finally(() => {
console.log('Promise settled');
});
Live Playground, Try it Yourself

Chaining Promises

You can chain multiple Promises together to handle the results of multiple asynchronous operations in sequence. Each then or catch method returns a new Promise that resolves to the return value of the handler function.

TypeScript
function fetchUser(id: number): Promise<string> {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id === 1) {
resolve('John Doe');
} else {
reject('User not found');
}
}, 1000);
});
}

fetchUser(1)
.then(user => {
console.log(`User's name is ${user}`);
return `User data: ${user}, age: 30`;
})
.then(userData => {
console.log(userData);
})
.catch(error => {
console.error(error);
});
Live Playground, Try it Yourself

Conclusion

In this tutorial, we have explored Promises in TypeScript, which provide a more structured and readable way to handle asynchronous tasks, avoiding the callback hell issue. As you continue learning TypeScript, make sure to practice using Promises, along with other async programming techniques like callbacks and async/await, to manage asynchronous tasks efficiently in your applications.