Asynchronous programming in TypeScript allows you to execute tasks concurrently, enabling non-blocking execution of code. This chapter explores asynchronous programming in TypeScript from basic to advanced concepts, covering topics such as callbacks, promises, async/await, error handling, and more. Through detailed explanations and examples, you'll gain a comprehensive understanding of how to effectively handle asynchronous operations in TypeScript.
Asynchronous programming is a programming paradigm that enables tasks to be executed concurrently, allowing programs to continue executing while waiting for certain operations to complete. This is particularly useful for I/O-bound tasks such as fetching data from a server or reading files.
Callbacks are a common mechanism for handling asynchronous operations in JavaScript and TypeScript. A callback function is passed as an argument to an asynchronous function and is executed once the operation completes.
function fetchData(callback: (data: any) => void) {
setTimeout(() => {
const data = 'Async Data';
callback(data);
}, 1000);
}
fetchData((data) => {
console.log('Data received:', data);
});
fetchData
function simulates an asynchronous operation using setTimeout
.Promises provide a cleaner and more structured way to handle asynchronous operations compared to callbacks. A promise represents a value that may be available now, in the future, or never.
function fetchData(): Promise {
return new Promise((resolve) => {
setTimeout(() => {
const data = 'Async Data';
resolve(data);
}, 1000);
});
}
fetchData()
.then((data) => {
console.log('Data received:', data);
});
fetchData
function returns a promise that resolves with the data after a timeout.then
method is used to handle the resolved value of the promise.Async/await is a modern syntax for handling asynchronous operations in a synchronous-like manner. It allows you to write asynchronous code that looks similar to synchronous code, making it easier to understand and maintain.
async function fetchData(): Promise {
return new Promise((resolve) => {
setTimeout(() => {
const data = 'Async Data';
resolve(data);
}, 1000);
});
}
async function getData() {
const data = await fetchData();
console.log('Data received:', data);
}
getData();
fetchData
function returns a promise.getData
function is declared as async
and uses await
to wait for the promise to resolve before continuing execution.Proper error handling is essential in asynchronous programming to handle exceptions and errors that may occur during execution.
async function fetchData(): Promise {
return new Promise((resolve, reject) => {
setTimeout(() => {
const error = false;
if (error) {
reject('Error fetching data');
} else {
const data = 'Async Data';
resolve(data);
}
}, 1000);
});
}
async function getData() {
try {
const data = await fetchData();
console.log('Data received:', data);
} catch (error) {
console.error('Error:', error);
}
}
getData();
fetchData
function can reject the promise with an error message if an error occurs.getData
function uses a try...catch
block to handle potential errors.One of the most common use cases of asynchronous programming in web development is fetching data from an API.
async function fetchDataFromAPI(): Promise {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('Failed to fetch data');
}
return await response.json();
}
async function processData() {
try {
const data = await fetchDataFromAPI();
console.log('Data from API:', data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
processData();
fetchDataFromAPI
function uses the fetch
API to make an HTTP request to an API endpoint.processData
function handles the retrieved data or logs an error if fetching fails.Asynchronous programming is a fundamental aspect of modern web development, and TypeScript provides powerful tools for managing asynchronous operations effectively. By understanding the basics of callbacks, promises, async/await, and error handling, you can write asynchronous code that is clean, readable, and maintainable. Happy coding! ❤️