Typescript promises
Created By: chatGPT
Promises in TypeScript are a way to handle asynchronous operations. A promise represents a value that may be available now, or in the future, or never. It can be in one of three states: pending, fulfilled, or rejected.
const myPromise = new Promise((resolve, reject) => {
// Simulating an asynchronous operation
setTimeout(() => {
const success = true;
if (success) {
resolve('Operation was successful!');
} else {
reject('Operation failed!');
}
}, 1000);
});
You can use the
then
method to handle a fulfilled promise and the catch
method to handle a rejected promise. This allows you to work with the result of the asynchronous operation conveniently.myPromise
.then(result => {
console.log(result); // Will log: Operation was successful!
})
.catch(error => {
console.error(error);
});
TypeScript provides a way to specify the type of value the promise will return. This makes it easier to work with the promise's result within your application by providing type safety.
const stringPromise: Promise<string> = new Promise((resolve) => {
resolve('Hello, TypeScript!');
});
You can also use the async/await syntax with promises to make your code cleaner and easier to read. By marking a function as
async
, you can use the await
keyword to wait for a promise to resolve.const asyncFunction = async () => {
try {
const result = await myPromise;
console.log(result); // Will log: Operation was successful!
} catch (error) {
console.error(error);
}
};
asyncFunction();
Using Promise.all allows you to execute multiple promises in parallel, and it returns a single promise that resolves when all of the promises have fulfilled or one has rejected.
const promise1 = Promise.resolve('First promise');
const promise2 = Promise.resolve('Second promise');
Promise.all([promise1, promise2])
.then((results) => {
console.log(results); // Will log: ['First promise', 'Second promise']
})
.catch((error) => {
console.error(error);
});