首页 > 解决方案 > 在 javascript / node js 中编写处理错误处理 then-catch 或 try-catch 是最佳实践

问题描述

我怀疑我写了一个程序,如果我的循环中发生任何错误,我很困惑用什么来处理,这是编写处理错误处理的最佳实践

我应该在循环中使用then catchor作为输出try catchfor 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:欢迎投反对票,但需要适当的解释,这是编写的最佳实践

标签: javascriptnode.jsfor-looptry-catch

解决方案


.catch()vs.try/catch在某种程度上是个人喜好,它还取决于您希望代码如何运行。通常,你会使用try/catchwithawait.catch()when not using await,但也有例外。此外,您通常不会.then()在使用await. 的全部意义await在于避免.then()它导致的嵌套代码。

在里面,你的for循环,await没有一个.then()vs. .then()withawait给出完全不同的结果。一个提供异步操作的并行运行,另一个提供异步操作的顺序运行,因为for循环暂停直到await完成。

因此,您使用可以为您提供所需行为的那个。然后,选择匹配的错误处理方法(通常是try/catchwithawait.catch()with -)。.then()


推荐阅读