I was practicing promise and this exercise popped up. I knew the throw will immediately hop out of the the function and find the nearest .catch. However, I still don't understand why return new Error('test'); is followed by the action of .then and not .catch.
Code snippet
function job(state) {
return new Promise(function(resolve, reject) {
if (state) {
resolve('success');
} else {
reject('error');
}
});
}
let promise = job(true);
promise
.then(function(data) {
console.log(data);
return job(true);
})
.then(function(data) {
if (data !== 'victory') {
throw 'Defeat';
}
return job(true);
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log(error);
return job(false);
})
.then(function(data) {
console.log(data);
return job(true);
})
.catch(function(error) {
console.log(error);
return 'Error caught';
})
.then(function(data) {
console.log(data);
return new Error('test');
})
.then(function(data) {
console.log('Success:', data.message);
})
.catch(function(data) {
console.log('Error:', data.message);
});
The result
> "success"
> "Defeat"
> "error"
> "Error caught"
> "Success:" "test"
I have researched but I can't seem to find any explanation on this matter. I also consulted chatGPT but it really sucked.
Erroris no different than returning anObjector astringor something - it's just some data. Yeah, you explicitly call it anError, but since you aren't telling Javascript to treat it as such it just assumes your method actually needed to return that. Like, what if your promise is something likeResolveToErrorMessage, would you expect it to resolve in thecatchblock? It's kind of stupid, but it keeps things versatile enough.thrown - but it isn't.