Javascript promises
Created By: chatGPT
A Promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. A promise can be in one of three states: pending, fulfilled, or rejected. Understanding how to use promises is essential for managing asynchronous operations in your code.
// Creating a new promise
let myPromise = new Promise((resolve, reject) => {
// Simulate a successful asynchronous operation
setTimeout(() => {
let success = true;
if (success) {
resolve('Operation successful!');
} else {
reject('Operation failed!');
}
}, 2000);
});
To use a promise, you attach the
.then()
method to handle the fulfilled state and the .catch()
method to handle the rejected state. This provides a clear and concise way to respond to the outcome of the asynchronous operation.myPromise
.then(result => {
console.log(result); // Output: Operation successful!
})
.catch(error => {
console.error(error);
});
You can also chain multiple Promises together. Each
then
only executes after the previous promise is fulfilled. If one of them is rejected, the control goes directly to the nearest catch
handler.let anotherPromise = myPromise
.then(result => {
console.log(result);
return 'Next operation';
})
.then(nextResult => {
console.log(nextResult);
})
.catch(error => {
console.error('Error:', error);
});
In addition to handling multiple promises in sequence, you may want to run multiple promises concurrently. You can use
Promise.all()
to execute several promises at once, returning a single promise that resolves when all of the promises in the array have resolved.let promise1 = Promise.resolve('First promise');
let promise2 = Promise.resolve('Second promise');
Promise.all([promise1, promise2])
.then(results => {
console.log(results); // Output: [ 'First promise', 'Second promise' ]
})
.catch(error => {
console.error('One of the promises failed:', error);
});