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.
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.
Familiarity with TypeScript and basic understanding of synchronous vs asynchronous programming is recommended.
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");
});
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);
}
}
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.
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.
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.
Write a function that returns a Promise which resolves with the value "Hello, World!" after 2 seconds.
function helloWorldPromise(): Promise<string> {
return new Promise(resolve => {
setTimeout(() => {
resolve("Hello, World!");
}, 2000);
});
}
helloWorldPromise().then(console.log); // "Hello, World!"
Write an async function that waits for the Promise from Exercise 1 to resolve, and then logs the value to the console.
async function logHelloWorld() {
let message = await helloWorldPromise();
console.log(message); // "Hello, World!"
}
logHelloWorld();
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.