Handling asynchronous code with Promises in TypeScript is a common task, and TypeScript provides strong support for working with Promises. Here's a basic guide on how to handle asynchronous code with Promises in TypeScript:
Defining a Promise:
Start by defining a function that returns a Promise
. The Promise
constructor takes a function with two arguments: resolve
and reject
.
typescriptfunction asyncFunction(): Promise<string> {
return new Promise((resolve, reject) => {
// Asynchronous code here
// If successful, call resolve with the result
// If there's an error, call reject with the error
});
}
Using async/await
:
TypeScript allows you to use async
and await
to write asynchronous code in a more synchronous-looking manner. Use the async
keyword with a function that contains asynchronous operations, and then use await
to wait for the promise to resolve.
typescriptasync function doAsyncOperation(): Promise<void> {
try {
const result = await asyncFunction();
console.log(result);
} catch (error) {
console.error(error);
}
}
doAsyncOperation();
Handling Promise Results:
When dealing with promises, you can use .then()
and .catch()
to handle the resolved value or the rejection.
typescriptasyncFunction()
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error);
});
Promise Chaining:
You can chain multiple promises using .then()
.
typescriptasyncFunction()
.then(result => {
return anotherAsyncFunction(result);
})
.then(finalResult => {
console.log(finalResult);
})
.catch(error => {
console.error(error);
});
Type Safety with Generics: If your asynchronous function returns a specific type, use generics to enforce type safety.
typescriptfunction asyncFunction<T>(): Promise<T> {
return new Promise((resolve, reject) => {
// Asynchronous code here
});
}
asyncFunction<string>()
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error);
});
Remember that TypeScript helps catch potential errors at compile-time, providing better type safety when working with Promises. Ensure that your TypeScript configuration has the --strict
flag enabled for maximum type safety.