In TypeScript, asynchronous operations can be effectively handled using promises. Promises provide a way to work with asynchronous code in a more structured and manageable manner. Let's dive into how promises can be used to handle asynchronous operations in TypeScript:
1. Creating Promises:
To handle asynchronous operations using promises, you typically create a promise object. The promise constructor takes a callback function with two parameters: `resolve` and `reject`. Inside this callback function, you perform your asynchronous task and call `resolve` when the task is successful or `reject` when it encounters an error. For example:
```
typescript`const myAsyncTask = (): Promise<string> => {
return new Promise((resolve, reject) => {
// Asynchronous task
setTimeout(() => {
const randomValue = Math.random();
if (randomValue < 0.5) {
resolve('Task completed successfully.');
} else {
reject(new Error('Task encountered an error.'));
}
}, 2000);
});
};`
```
2. Consuming Promises:
O....
Log in to view the answer