How to use Async/Await with a Promise in TypeScript ?
Last Updated :
12 Jul, 2024
In TypeScript, you can use async and await with a Promise to simplify asynchronous code and make it more readable.
What is a Promise?
A promise in TypeScript is an object representing the eventual completion or failure of an asynchronous operation. It acts as a placeholder for a value that may be available now, in the future, or never.
Syntax:
const myPromise = new Promise((resolve, reject) => {
// Asynchronous operation or task
// If successful, call resolve with the result
// If there's an error, call reject with the reason
});
A promise is typically created using the Promise constructor, which takes a callback function with resolve and reject parameters. The asynchronous operation is performed inside this callback.
Why Use Async/Await with a Promise in TypeScript?
The async/await syntax in TypeScript provides a more concise and readable way to work with promises. It makes asynchronous code look and behave like synchronous code, making it easier to understand.
Using async/await with promises helps avoid the callback hell (also known as the pyramid of doom) and makes error handling more straightforward.
Steps to Use async/await
with a Promise in TypeScript
1. Create an Asynchronous Function
Use the async keyword before a function declaration to indicate that it contains asynchronous code.
TypeScript
async function myAsyncFunction(): Promise<void> {
// Asynchronous code with await keyword
try {
const result = await myPromiseFunction();
// Process result
} catch (error) {
// Handle errors
}
}
2. Use the await Keyword
Inside the asynchronous function, use the await keyword before calling a promise. This pauses the execution of the function until the promise is resolved or rejected.
TypeScript
async function myAsyncFunction(): Promise<void> {
try {
const result = await myPromiseFunction();
// Process result
} catch (error) {
// Handle errors
}
}
Example
Here, fetchData returns a promise, and fetchDataAsync is an asynchronous function that uses await to wait for the promise to be resolved. The try/catch block handles any errors that might occur during the asynchronous operation.
TypeScript
// Function returning a promise
function fetchData(): Promise<string> {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Async data has been fetched!");
}, 2000);
});
}
// Async function using await to handle the promise
async function fetchDataAsync(): Promise<void> {
try {
const result = await fetchData();
console.log(result); // Output: Async data has been fetched!
} catch (error) {
console.error("Error fetching data:", error);
}
}
// Call the async function
fetchDataAsync();
Output:
Async data has been fetched!