我一直在阅读新的 async/await 并在 Node 8 中使用它。我遇到过一些人将所有内容都放在初始 try
block 中,还有一些人只有 await
,其余的都在 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
,这是 async
函数的默认行为。
您的两个代码片段的不同之处在于第一种情况下的 throw new Error(...
将由 catch
子句处理。但是由于 catch
子句对于所有实际目的来说都是无操作、传递,这并不重要。
我会把它写成:
async function findCurrentInstallations() {
const results = await installations.find({});
if (results.length === 0) { throw new Error('No installations registered'); }
return results;
}
关于javascript - async/await 代码是否应该完全包含在 try block 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44473525/