I was reading some posts and got similar question in interview. Lets say the code snippet looks like this:
const newPromise = new Promise((resolve, reject) => reject());
newPromise
.then(() => { console.log("1") })
.catch((error) => { console.log("2"); })
.then(() => {
console.log("3");
throw new Error;
})
.then(() => console.log("4"))
.catch(() => console.log("5"))
.catch(() => console.log("6"))
So by looking at this, my first thought was that since the Promise “instantly” rejects, it will look for the closest catch, handle the “error” and exit the Promise cycle.
As it turns out there are 2 scenarious what can happen after that catch method:
- If it handles the error or you call
Promise.resolve(), then the Promise switches back to fullfilled state and it will look for the firstthenmethod. - If it rethrows the errors or you call
Promise.reject()it will propogate the error, promise stays in the rejection state and it will look for the closestcatchmethod.
So my question is – how can we simple exit / terminate the Promise process from either then or catch callbacks, if we end up in this “callback hell” scenario?
What I tried:
Without returning anything, it goes to fulfill state, which means nearest then is executed.
Then I tried to simply return any value, it results in Promise going in to “fulfill” state.
Then I tried either Promise.reject() or Promise.resolve() – same result as above respectively.
