【问题标题】:which is best practice to write to handle error handling then-catch or try-catch in javascript / node js [duplicate]这是编写以在javascript / node js中处理错误处理then-catch或try-catch的最佳实践[重复]
【发布时间】:2021-10-02 02:09:57
【问题描述】:

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

我应该在我的for of 循环中使用then catchtry catch 作为输出

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:欢迎投反对票,但需要适当的解释,这是编写的最佳实践

【问题讨论】:

  • 在一个函数中混合 async/await.then .catch (几乎)总是错误的代码 - 选择一个并坚持下去
  • 这是个人喜好。通常,当不使用await 时,您会使用try/catchawait.catch(),但也有例外。此外,在使用await 时,您通常不会使用.then()await 的全部意义在于避免 .then() 及其导致的嵌套代码。
  • 所以我应该使用 try catch 吗? @布拉沃
  • 查看 jfriend00 之前的评论 - 这不取决于我,也不取决于他,这完全取决于您 - 在两段代码中,第二段可以说是“更好”,因为它没有混合async/await 与 .then/.catch - 所以在这方面 - 下定决心
  • 在内部,for 循环,await.then() 给出完全不同的结果。一种提供异步操作的并行运行,另一种提供异步操作的顺序运行。因此,您使用可以为您提供所需行为的那个。然后,选择匹配的错误处理方法(try/catchawait.catch().then())。

标签: javascript node.js for-loop try-catch


【解决方案1】:

.catch()try/catch 有点个人偏好,这也取决于您希望代码如何运行。通常,当不使用await 时,您会使用try/catchawait.catch(),但也有例外。此外,在使用await 时,您通常不会使用.then()await 的全部意义在于避免 .then() 及其导致的嵌套代码。

在内部,您的for 循环、没有.then()await 与带有await.then() 给出完全不同的结果。一个提供异步操作的并行运行,另一个提供异步操作的顺序运行,因为for 循环暂停,直到await 完成。

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

【讨论】:

  • "在你的 for 循环中,await.then() 给出完全不同的结果。" - OP 在两个 sn-ps 中都有 await
  • @Bergi - 是的,我已经澄清了我在这方面的答案。但是,问题的实质是关于.catch()try/catch
猜你喜欢
  • 2011-03-26
  • 1970-01-01
  • 2013-02-05
  • 1970-01-01
  • 1970-01-01
  • 2020-08-17
  • 1970-01-01
  • 2019-11-14
  • 1970-01-01
相关资源
最近更新 更多