How to use Async/Await with a Promise in TypeScript ?
In TypeScript, you can use async
and await
with a Promise to simplify asynchronous code and make it more readable.
Promise
A promise in TypeScript is an object representing the eventual completion or failure of an asynchronous operation. It is a placeholder for a value that may be available now, or 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
Create an asynchronous function
- Use the
async
keyword before a function declaration to indicate that it contains asynchronous code.
async function myAsyncFunction(): Promise<void> {
// Asynchronous code with await keyword
try {
const result = await myPromiseFunction();
// Process result
} catch (error) {
// Handle errors
}
}
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.
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.
Javascript
// Function returning a promise function fetchData(): Promise<string> { return new Promise((resolve, reject) => { // Simulating an asynchronous operation // (e.g., fetching data) setTimeout(() => { const data = "Async data has been fetched!" ; resolve(data); }, 2000); }); } // Asynchronous function using async/await async function fetchDataAsync() { try { const result = await fetchData(); console.log(result); } catch (error) { console.error( "Error fetching data:" , error); } } // Call the asynchronous function fetchDataAsync(); |
Output:
Async data has been fetched!