javascript - 你如何在 Javascript 中逃避 try/catch 地狱?
问题描述
好的,我喜欢(d)用等待/异步尝试/捕获。
但是我该怎么办。
我想这样做..
let a = await doAbc();
let b = await do123(a);
相反,它变成了
let a, b;
try {
a = await doAbc();
} catch(e) {
a = await doZxc();
}
try {
b = await do123(a);
} catch (e) {
console.log(e);
return;
}
if (b.data == undefined) {
return -1;
} else {
return b;
}
在这一点上,我对一切感到后悔。
解决方案
请记住,您可以await
做出任何承诺。所以你可以这样做:
let a = await doAbc().catch(doZxc); // or .catch(() => doZxc())
let b = await do123(a);
甚至
let b = await doAbc().catch(doZxc).then(do123);
连同您的其余代码:
try {
let b = await doAbc().catch(doZxc).then(do123);
return b.data == undefined ? -1 : b;
} catch (e) {
console.log(e);
return;
}
推荐阅读
- pine-script - 从自定义输入设置策略佣金类型
- javascript - 我需要这个数组解决方案,有什么办法吗?
- vue.js - 如何在 Vee Validate 4 中正确使用组合 API 和自定义字段
- javascript - Javascript - 在事件处理程序中仅在一个案例(开关案例)内调用异步函数
- html - Angular CLI 按钮(单击)不调用方法
- java - 首次使用 vscode 时的 Java 编译问题
- javascript - 开放银行 api 与 ASP.NET MVC 的集成
- azure-devops - 在 Azure Devops 中部署发布管道时出错
- ios - 如何在ffmpeg中添加具有相同视频纵横比的视频开头的介绍图像?
- robotframework - 如何在第一次循环迭代后获取更改的内容(字符串)以用于 Robot 框架的下一次迭代