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:
- Pending: The initial state; neither fulfilled nor rejected.
- Fulfilled: The operation completed successfully, and the Promise has a resulting value.
- 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.
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.
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.
myPromise
.then(value => {
console.log(value); // Output: Promise resolved!
})
.catch(reason => {
console.error(reason);
})
.finally(() => {
console.log('Promise settled');
});
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.
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);
});
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.