Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to create asynchronous function in TypeScript?
Asynchronous programming allows us to perform multiple tasks without blocking code execution. In TypeScript, we use the async/await keywords to create asynchronous functions that handle promises elegantly.
Before diving in, let's understand why asynchronous programming is essential. When fetching data from APIs or performing I/O operations, these tasks take time to complete. In single-threaded languages like TypeScript and JavaScript, synchronous code would block execution until the operation finishes, leading to poor performance.
Asynchronous functions solve this by allowing other code to execute while waiting for time-consuming operations to complete. The await keyword pauses execution only within the async function, not the entire program.
Syntax
Here's the basic syntax for creating asynchronous functions in TypeScript:
async function functionName(): Promise<ReturnType> {
const result = await someAsyncOperation();
return result;
}
// Arrow function syntax
const asyncFunction = async (): Promise<ReturnType> => {
const result = await someAsyncOperation();
return result;
};
The async keyword marks a function as asynchronous and automatically wraps the return value in a Promise. The await keyword pauses execution until the promise resolves.
Example 1: Basic Async Function
This example demonstrates how async functions execute asynchronously while other code continues running:
async function test(): Promise<void> {
let data: string = await "default string";
console.log("The value of data is " + data);
}
console.log("Before function execution");
test();
console.log("After function execution");
Before function execution After function execution The value of data is default string
Notice that "After function execution" prints before the async function completes, demonstrating non-blocking behavior.
Example 2: Working with Promises
This example shows how async functions handle actual promises with proper error handling:
async function samplePromise(): Promise<string> {
const newPromise = new Promise<string>((resolve, reject) => {
setTimeout(() => {
resolve("Successfully resolved after delay");
}, 1000);
});
return newPromise;
}
async function executeAsync(): Promise<void> {
try {
let response = await samplePromise();
console.log(response);
} catch (err) {
console.log("Error is " + err);
}
}
console.log("Before calling async function");
executeAsync();
console.log("After calling async function");
Before calling async function After calling async function Successfully resolved after delay
Example 3: Fetching Data
Here's a practical example simulating API data fetching:
interface User {
id: number;
name: string;
}
async function fetchUserData(userId: number): Promise<User> {
// Simulating API call with setTimeout
return new Promise((resolve) => {
setTimeout(() => {
resolve({ id: userId, name: `User ${userId}` });
}, 500);
});
}
async function displayUserInfo(): Promise<void> {
try {
console.log("Fetching user data...");
const user = await fetchUserData(123);
console.log(`User ID: ${user.id}, Name: ${user.name}`);
} catch (error) {
console.error("Failed to fetch user:", error);
}
}
displayUserInfo();
Fetching user data... User ID: 123, Name: User 123
Key Points
-
Type Safety: Always specify return types as
Promise<T>for async functions - Error Handling: Use try/catch blocks with async/await
- Non-blocking: Async functions don't block other code execution
- Promise-based: Async functions automatically return promises
Conclusion
Asynchronous functions in TypeScript provide a clean way to handle promises and non-blocking operations. They improve application performance by preventing blocking operations from freezing the execution thread while maintaining readable, synchronous-looking code.
