Introduction
In this section, we will explore the async and await keywords in TypeScript, which provide a more readable and straightforward way to handle asynchronous operations compared to traditional promise chaining. By the end of this section, you will understand how to use async and await to write cleaner and more maintainable asynchronous code.
Key Concepts
- Async Functions: Functions declared with the
asynckeyword. - Await Keyword: Used to pause the execution of an
asyncfunction until a promise is resolved. - Error Handling: Using
try...catchblocks to handle errors inasyncfunctions.
Async Functions
An async function is a function that returns a promise. The async keyword is placed before the function declaration.
Example
In this example, fetchData is an async function that returns a promise which resolves to the string "Data fetched".
Await Keyword
The await keyword can only be used inside async functions. It pauses the execution of the function until the promise is resolved.
Example
async function fetchData(): Promise<string> {
return "Data fetched";
}
async function processData() {
const data = await fetchData();
console.log(data); // Output: Data fetched
}
processData();In this example, await fetchData() pauses the execution of processData until fetchData resolves, and then assigns the resolved value to data.
Error Handling
Errors in async functions can be caught using try...catch blocks.
Example
async function fetchData(): Promise<string> {
throw new Error("Failed to fetch data");
}
async function processData() {
try {
const data = await fetchData();
console.log(data);
} catch (error) {
console.error("Error:", error.message); // Output: Error: Failed to fetch data
}
}
processData();In this example, if fetchData throws an error, it is caught in the catch block, and the error message is logged to the console.
Practical Example: Fetching Data from an API
Let's see a practical example of using async and await to fetch data from an API.
Example
async function fetchUserData(userId: number): Promise<any> {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
if (!response.ok) {
throw new Error("Network response was not ok");
}
const data = await response.json();
return data;
}
async function displayUserData(userId: number) {
try {
const userData = await fetchUserData(userId);
console.log(userData);
} catch (error) {
console.error("Error fetching user data:", error.message);
}
}
displayUserData(1);In this example:
fetchUserDatais anasyncfunction that fetches user data from an API.displayUserDatais anasyncfunction that callsfetchUserDataand handles any errors that may occur.
Exercises
Exercise 1: Basic Async/Await
Write an async function getNumber that returns a promise resolving to the number 42. Then, write another async function printNumber that uses await to get the number from getNumber and logs it to the console.
Solution
async function getNumber(): Promise<number> {
return 42;
}
async function printNumber() {
const number = await getNumber();
console.log(number); // Output: 42
}
printNumber();Exercise 2: Error Handling
Modify the getNumber function to throw an error with the message "Something went wrong". Update the printNumber function to handle this error and log "Error: Something went wrong" to the console.
Solution
async function getNumber(): Promise<number> {
throw new Error("Something went wrong");
}
async function printNumber() {
try {
const number = await getNumber();
console.log(number);
} catch (error) {
console.error("Error:", error.message); // Output: Error: Something went wrong
}
}
printNumber();Conclusion
In this section, we covered the basics of async and await in TypeScript. We learned how to declare async functions, use the await keyword to pause execution until a promise is resolved, and handle errors using try...catch blocks. We also saw practical examples and exercises to reinforce these concepts. In the next section, we will explore working with APIs in more detail.
TypeScript Course
Module 1: Introduction to TypeScript
- What is TypeScript?
- Setting Up the TypeScript Environment
- Basic Types
- Type Annotations
- Compiling TypeScript
Module 2: Working with Types
Module 3: Advanced Types
Module 4: Functions and Modules
Module 5: Asynchronous Programming
Module 6: Tooling and Best Practices
- Linting and Formatting
- Testing TypeScript Code
- TypeScript with Webpack
- TypeScript with React
- Best Practices
