【发布时间】:2017-11-12 09:36:25
【问题描述】:
我一直在阅读新的 async/await 并一直在 Node 8 中使用它。我遇到一些人将所有内容都放在最初的 try 块中,而其他人只有 @987654322 @ 其余的都在 try/catch 之下。这个比那个好吗?这是我自己代码中的函数之一,以两种样式显示我的意思:
async function findCurrentInstallations() {
try {
const results = await installations.find({});
if (results.length === 0) { throw new Error('No installations registered'); }
return results;
} catch (err) {
throw err;
}
}
--
async function findCurrentInstallations() {
let results;
try {
results = await installations.find({});
} catch (err) {
throw err;
}
if (results.length === 0) { throw new Error('No installations registered'); }
return results;
}
【问题讨论】:
-
为什么你会捕获一个错误只是为了立即再次抛出它?你甚至没有记录错误。这两个
try ... catch块完全没有意义。 -
@Thomas 因为我还在学习这个并且还不能 100% 确定我在做什么?一个回应基本上是说“你这个白痴,你到底为什么这样做?”没有帮助。
-
不,我的意思是“这些
try...catch块毫无意义。根本没有理由这样做。它们不会为您的代码增加任何价值,甚至连记录错误都没有在重新扔之前”。我既没有说,也没有说“你这个白痴”;抱歉,如果遇到这样的情况。不是“你为什么要那样做?”一个有效的问题了吗?也许更多的是一个需要思考的问题,一个重新思考你的动作/代码的提示,而不是一个期望得到实际答案的问题。 -
别担心,这该死的纯文本媒体让语气难以确定!感谢您的澄清。 :)
-
async/await是 ES2017 的一部分,不是 ES7!
标签: javascript async-await ecmascript-2017