I have the code below, as long as my function doesn’t have async
keyword at the beginning of it, there is no problem catching the exception at the function call but when I add async
keyword to the function, I’m unable to catch the exception at the function call, I’m just wondering why it’s not possible to catch the exception at the function call in an async
function?
p.n: I know I can catch thee exception inside the body of the async
function, I’m just wondering why it’s not possible in the function call.
code:
//async function
async function lome() {
throw new Error("error");
}
try { lome() } catch { console.log("hey") };
//output: error
//normal function
function lome() {
throw new Error("error");
}
try { lome() } catch { console.log("hey") };
//output:hey
p.n2: it’s not possible to add await
next to my function call, and if you mean I have to use await
inside my async
function body, still it’s not helping to catch the error.
code:
async function lome() {
throw new Error("error");
}
try { await lome() } catch { console.log("hey") };
//output: Uncaught SyntaxError: await is only valid in async
//functions and the top level bodies of modules.
async function lome() {
return await Promise.reject(99)
}
try { lome() } catch { console.log("hey") }
//output: error(I have tested with and without `return` keyword).
12