Reputation: 25
I'm doing try and catch exercises in JavaScript.
here is my code
function getTime1() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(11111);
}, 1000);
});
}
function getTime2() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(22222);
}, 1000);
});
}
async function funB() {
// try {
let b = await getTime2();
throw "B error";
// } catch (e) {
// console.log("this" + e);
// }
}
async function funA() {
try {
let a = await getTime1();
funB();
} catch (e) {
console.log("that" + e);
}
}
funA();
and here is the result
Uncaught (in promise) B error
I want to know why there is no catch in funb and Funa. Thank you
Upvotes: 0
Views: 46
Reputation: 821
From my understanding try/catch doesn't work with async :
"Because errorTest is async, it will always return a promise and will never begin execution exactly where you call it: it is asynchronous. errorTest returns, and you exit the try block, before a single line of code within errorTest is run. Therefore, your catch block will never fire, because nothing in errorTest would synchronously throw an exception."
Source : Why is try {} .. catch() not working with async/await function?
Since async will return a Promise, I believe you'll need to use the catch on the Promise itself
funB().then((result) => {
console.log(result);
}).catch((error) => {
console.error(error);
});
Upvotes: 1