javascript - 在 catch 块中返回后继续执行函数
问题描述
使用 async / await,我尝试了两种不同的语法:
async function asyncFunc() {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject('promise rejected')
}, 500);
});
}
async function asyncCallWithoutTryCatchBlock() {
await asyncFunc().catch((err) => {
console.log('Catching error');
return;
});
console.log('Outside, after catch is called');
}
async function asyncCallWithTryCatchBlock() {
try {
await asyncFunc();
} catch(err) {
console.log('Catching error');
return;
}
console.log('Outside, after catch is called');
}
asyncCallWithoutTryCatchBlock();
asyncCallWithTryCatchBlock();
我期待这个输出:
Catching error
Catching error
我明白了:
Catching error
Outside, after catch is called
Catching error
我想知道为什么在我在块中进行显式返回时console.log
调用外部?asyncCallWithoutTryCatchBlock
catch
解决方案
返回值在您传递给 catch 方法的匿名函数内。因此,它仅从该匿名函数返回。作为函数中的最后一条语句,它实际上毫无用处。
两个代码片段之间的最大区别在于,一个使用语言结构 try catch,另一个使用称为 catch 的方法,该方法需要一个匿名函数。
推荐阅读
- python - 我可以在同一个异步循环中写入和读取进程吗?
- reactjs - 发布反应放大应用程序时如何为登台环境运行不同的构建命令
- docker - Django 应用程序退出多阶段构建映像
- powershell - 使用 powershell 更改计算机名称
- php - 使用 html 时的 Str_replace 问题
- java - Firebase .orderByChild - 尝试订购数字,但它只订购第一个数字
- iis - 如何增加失败请求日志的最大大小?
- docker - 不支持 Docker 撰写版本
- c# - IOptions 配置抛出随机 NullReferenceException - AspNetCore 2.2
- flutter - Flutter:部分材质设计图标不支持