这是在 javascript / node js 中编写错误处理 then-catch 或 try-catch 的最佳实践
which is best practice to write to handle error handling then-catch or try-catch in javascript / node js
我怀疑我写了一个程序,我很困惑如果我的循环中发生任何错误应该使用什么来处理,以及编写哪个是处理错误的最佳实践
我应该在 for of
循环中使用 then catch
还是 try 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:欢迎投反对票,但需要适当的解释,这是编写的最佳实践
.catch()
与 try/catch
在某种程度上是个人偏好,它还取决于您希望代码如何 运行。通常,当不使用 await
时,您会使用 try/catch
与 await
和 .catch()
,但也有例外。此外,您通常不会在使用 await
时使用 .then()
。 await
的全部意义在于避免 .then()
及其导致的嵌套代码。
在内部,您的 for
循环,没有 .then()
的 await
与带有 await
的 .then()
给出完全不同的结果。一个提供异步操作的并行 运行ning,另一个提供异步操作的顺序 运行ning,因为 for
循环暂停直到 await
完成。
因此,您可以使用能够为您提供所需行为的工具。然后,选择匹配的错误处理方法(try/catch
与 await
和 .catch()
与 .then()
- 通常)。
我怀疑我写了一个程序,我很困惑如果我的循环中发生任何错误应该使用什么来处理,以及编写哪个是处理错误的最佳实践
我应该在 for of
循环中使用 then catch
还是 try 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:欢迎投反对票,但需要适当的解释,这是编写的最佳实践
.catch()
与 try/catch
在某种程度上是个人偏好,它还取决于您希望代码如何 运行。通常,当不使用 await
时,您会使用 try/catch
与 await
和 .catch()
,但也有例外。此外,您通常不会在使用 await
时使用 .then()
。 await
的全部意义在于避免 .then()
及其导致的嵌套代码。
在内部,您的 for
循环,没有 .then()
的 await
与带有 await
的 .then()
给出完全不同的结果。一个提供异步操作的并行 运行ning,另一个提供异步操作的顺序 运行ning,因为 for
循环暂停直到 await
完成。
因此,您可以使用能够为您提供所需行为的工具。然后,选择匹配的错误处理方法(try/catch
与 await
和 .catch()
与 .then()
- 通常)。