I stumbled upon some code that looked off to me:
JavaScript
x
7
1
try {
2
somePromise()
3
.then(res => console.log(res));
4
} catch (err) {
5
console.error(err);
6
}
7
If some somePromise()
fails, would this not get caught, and the app would crash? Does this try-catch even do anything?
Should be this, correct?:
JavaScript
1
4
1
somePromise()
2
.then(res => console.log(res))
3
.catch(err => console.error(err));
4
Advertisement
Answer
TL;DR – If a function that returns a promise throws an exception before returning the promise then that exception would have to be caught in a regular try-catch block.
Consider this function
JavaScript
1
10
10
1
function asyncAdd(x,y){
2
if(x === 2){
3
throw new Error("good old exception")
4
}else if(x === 1) {
5
return Promise.reject("fancy exception")
6
}
7
8
return Promise.resolve(x+y)
9
}
10
This would print “Try caught good old exception”
JavaScript
1
6
1
try{
2
asyncAdd(2,10).then(x =>console.log("result", x)).catch(y => console.error("Promise caught", y));
3
}catch (e){
4
console.error("Try caught", e);
5
}
6
This would print “Promise caught fancy exception”
JavaScript
1
6
1
try{
2
asyncAdd(1,10).then(x =>console.log("result", x)).catch(y => console.error("Promise caught", y));
3
}catch (e){
4
console.error("Try caught", e);
5
}
6