TypeScript, being a typed superset of JavaScript, supports asynchronous programming via multiple mechanisms, one of the modern and widely used approaches is using ‘async/await‘. The ‘async‘ and ‘await‘ keywords allow us to write asynchronous code in a more synchronous and clean manner. This is achieved using Promises in the background.
Here’s a brief explanation of ‘Promise‘, ‘async‘, and ‘await‘:
1. **Promise**: A Promise is a JavaScript object representing the eventual completion or failure of an asynchronous operation. It allows attaching callbacks to handle the async return value or exception. A Promise is in one of the following 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.
- settled: The operation completed, whether fulfilled or rejected.
2. **async**: The ‘async‘ keyword is added before a function to declare it as asynchronous. An async function returns a ‘Promise‘ object. If the function has a return value, the ‘Promise‘ will be resolved with that value, otherwise, it’s resolved with ‘undefined‘.
3. **await**: The ‘await‘ keyword is used to wait for a ‘Promise‘ to resolve or reject, allowing the asynchronous operation to complete before proceeding to the next line of code. It can only be used within an ‘async‘ function.
Here’s a simple example demonstrating the usage of ‘async/await‘ in TypeScript:
// Simulate an async operation, like fetching data from a server
function fetchDataFromServer(): Promise<string> {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data from the server");
}, 2000);
});
}
// A function using async/await to call the async operation
async function processData(): Promise<void> {
console.log("Fetching data...");
const data = await fetchDataFromServer(); // Use 'await' to wait for the Promise to resolve
console.log("Data fetched:", data);
}
// Invoke the async function
processData();
In the example above:
1. ‘fetchDataFromServer‘ represents an asynchronous operation, like fetching data from a server, and returns a ‘Promise‘ containing the simulated data.
2. ‘processData‘ is declared as an ‘async‘ function. Inside the function, we use the ‘await‘ keyword before ‘fetchDataFromServer()‘ to wait for the completion of the async operation before moving to the next line of code, for example, to log the received data to the console.
When using this code, the output would be:
Fetching data...
(2 seconds pause)
Data fetched: Data from the server
To summarize, TypeScript supports asynchronous programming and provides a clean and readable way to handle asynchronous code using ‘async/await‘. This makes it more convenient to work with Promises and manage the flow of control in asynchronous operations.