简体   繁体   English

在一个表达式中结合 throw new Error 和 await

[英]Combine throw new Error with await in one expression

can I throw error and use await word in one statement using AND operator, the following code explains well my request :我可以使用AND运算符在一个语句中抛出错误并使用 await 字吗?以下代码很好地解释了我的请求:

throw new Error() && await client.end() . throw new Error() && await client.end()

This latter works fine till now, and for my question, is this the better form of writing this and will it create problems in some cases.后者到目前为止工作正常,对于我的问题,这是写这个更好的形式吗?它会在某些情况下产生问题。

My main purpose is to close the Data Base connection and throw the Error.我的主要目的是关闭数据库连接并抛出错误。

for such use cases I think the finally block is the right solution.对于这样的用例,我认为finally块是正确的解决方案。 See on the mozilla docs here .请参阅此处的 Mozilla 文档 In your case it would be something like在你的情况下,它会像

try {
    // stuff that can throw an error
} catch {
    // handle the error case
} finally {
    // in any case, close the connection
    await client.end()
}

Or, if you want to keep the connection open when there's no error, just move the close line in the catch block:或者,如果您想在没有错误的情况下保持连接打开,只需移动catch块中的关闭行:

try {
    // stuff that can throw an error
} catch {
    // handle the error case
    await client.end()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM