Javascript 为什么在异步函数的catch之后仍然会抛出异常
在本文中,我们将尝试理解异常在异步函数中何时被捕获以及何时被抛出和缓存。让我们通过编程示例来可视化问题陈述及其解决方案。
示例1: 我们将创建一个新的函数,使用 Promise.reject() 方法或 throw 语句抛出错误。我们将在另一个函数中捕获该 throw 错误,这个函数将成为 async() 函数,然后我们的代码的其余部分也会被执行,这是不必要的。
Javascript
let exception_thrown_method = () => {
return Promise.reject("Exception thrown...!!");
};
let catchException = async () => {
let msg = await exception_thrown_method().catch((error) =>
console.log("Caught Error: " + error)
);
console.log("Stop code's execution.....");
};
catchException();
输出:
Caught Error: Exception thrown...!!
Stop code's execution.....
示例2: 在 async() 函数中,我们将创建一个新的 try/catch 块。在 try 块中,我们将调用我们的第一个函数,该函数会抛出错误。在 catch 语句中,我们将捕获从第一个函数接收到的错误。在输出中,我们将看到只打印了捕获语句行,没有额外的行,这是我们想要的结果。
JavaScript
<script>
let exception_thrown_method = () => {
return Promise.reject("Exception thrown...!!");
};
let catchException = async () => {
try {
await exception_thrown_method();
console.log("Stop code's execution here only....!!");
} catch (error) {
console.log("Caught Error: " + error);
}
};
catchException();
</script>
输出:
Caught Error: Exception thrown...!!
示例3: 我们将对catchException()
方法以及async()
方法进行一些更改。在这个异步函数中,我们将创建一个变量来调用我们的方法,然后使用catch()
方法,然后返回”null”,看起来像是有一个标志变量。通过写一个空的返回语句来检查变量的值是否为null。在输出中,我们将看到没有额外的行被打印出来,只有必需的行被打印出来。
Javascript
<script>
let exception_thrown_method = () => {
return Promise.reject("Exception thrown...!!");
};
let catchException = async () => {
let result = await exception_thrown_method().catch((error) => {
console.log("Caught error: " + error);
return null;
});
if (result === null) {
return;
}
console.log("Stop code's execution here only...");
};
catchException();
</script>
输出:
Caught error: Exception thrown...!!