In TypeScript, you can use the async
and await
keywords to work with asynchronous code. To implement async/await
in TypeScript, you need to use functions that return promises and mark the function with the async
keyword. Here's a basic example:
typescript// Example function that returns a Promise
function delay(ms: number): Promise<string> {
return new Promise((resolve) => {
setTimeout(() => {
resolve(`Delayed for ${ms} milliseconds`);
}, ms);
});
}
// Example function using async/await
async function asyncExample() {
console.log('Start');
try {
const result1 = await delay(1000);
console.log(result1);
const result2 = await delay(2000);
console.log(result2);
} catch (error) {
console.error('Error:', error);
}
console.log('End');
}
// Call the async function
asyncExample();
In this example:
delay
function returns a promise that resolves after a specified number of milliseconds.asyncExample
function is marked as async
and uses the await
keyword to wait for the promises returned by the delay
function.try-catch
block is used to handle any errors that might occur during the asynchronous operations.Make sure to set the target ECMAScript version to ES2017 or later in your TypeScript configuration to support the async/await
syntax. You can do this by adding the following compiler options to your tsconfig.json
file:
json{
"compilerOptions": {
"target": "es2017",
"lib": ["es2017"]
}
}
This ensures that the generated JavaScript code supports the async/await
syntax.