I am new to Javascript now and trying to learn it. The firstPromise will reject and run the catch
instead of then
. Now, I want it to skip all the other then
‘s and goes to finally
.
// Define the first promise
function firstPromise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject('First promise rejected'); // or resolve('First promise resolved') to test success
}, 1000);
});
}
// Define the second promise
function secondPromise(result) {
return new Promise((resolve, reject) => {
console.log('Second promise received:', result);
resolve('Second promise resolved');
});
}
// Define the third promise
function thirdPromise(result) {
return new Promise((resolve, reject) => {
console.log('Third promise received:', result);
resolve('Third promise resolved');
});
}
// Chain the promises
firstPromise()
.then(result => {
console.log('First then:', result);
return secondPromise(result);
})
.catch(error => {
console.error('First catch:', error);
// Return a resolved promise to stop further .then or .catch handlers
return Promise.resolve();
})
.then(result => {
// This will not be called because the previous .catch returned a resolved promise
console.log('Second then:', result);
return thirdPromise(result);
})
.catch(error => {
// This will not be called because the previous .catch returned a resolved promise
console.error('Second catch:', error);
})
.finally(() => {
console.log('Finally block');
});