javascript - 在 javascript / node js 中编写处理错误处理 then-catch 或 try-catch 是最佳实践
问题描述
我怀疑我写了一个程序,如果我的循环中发生任何错误,我很困惑用什么来处理,这是编写处理错误处理的最佳实践
我应该在循环中使用then catch
or作为输出try catch
for of
for (value of Data){
test = await getValue(value)
.then((obj)=>{
// some code})
.catch((err)=>{
console.log(err);});
}
for (value of Data){
try{
test= await getValue(value);
}
catch (e){
console.log(e);
}
Ps:欢迎投反对票,但需要适当的解释,这是编写的最佳实践
解决方案
.catch()
vs.try/catch
在某种程度上是个人喜好,它还取决于您希望代码如何运行。通常,你会使用try/catch
withawait
和.catch()
when not using await
,但也有例外。此外,您通常不会.then()
在使用await
. 的全部意义await
在于避免.then()
它导致的嵌套代码。
在里面,你的for
循环,await
没有一个.then()
vs. .then()
withawait
给出完全不同的结果。一个提供异步操作的并行运行,另一个提供异步操作的顺序运行,因为for
循环暂停直到await
完成。
因此,您使用可以为您提供所需行为的那个。然后,选择匹配的错误处理方法(通常是try/catch
withawait
和.catch()
with -)。.then()
推荐阅读
- java - 如何导出旧密钥库的客户端证书并在我的中使用它
- django - 如何在 django rest 中并行运行两个请求
- ruby-on-rails - 如何使用特定的 COLLATE 创建迁移?
- typescript - Google Cloud Functions - 自定义构建步骤
- python - “NoneType”对象没有属性“find_all”
- spring - 问题映射字段 ModelMapper
- jsf - Wildflt 13 WELD-001304:范围类型 javax.enterprise.context.SessionScoped 的多个上下文处于活动状态
- python - 如何从 django 中删除记录?
- php - Laravel 6 错误 Action Facade\Ignition\Http\Controllers\ShareReportController not defined 是什么意思?
- php - 如何在表格中显示二叉树数据