正确尝试...使用Async / Await捕获语法 [英] Correct Try...Catch Syntax Using Async/Await

查看:174
本文介绍了正确尝试...使用Async / Await捕获语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢在Typescript等中提供的新 Async / Await 功能的平坦性。但是,我不确定我喜欢我必须声明的事实变量我 await try ... catch 块的外部以便稍后使用它。像这样:

I like the flatness of the new Async/Await feature available in Typescript, etc. However, I'm not sure I like the fact that I have to declare the variable I'm awaiting on the outside of a try...catch block in order to use it later. Like so:

let createdUser
try {
    createdUser = await this.User.create(userInfo)
} catch (error) {
    console.error(error)
}

console.log(createdUser)
// business
// logic
// goes
// here

请纠正我我错了,但似乎最好的做法尝试主体中放置多行业务逻辑,所以我离开了只能在块外声明 createdUser ,在块中指定它,然后在块之后使用它。

Please correct me if I'm wrong, but it seems to be best practice not to place multiple lines of business logic in the try body, so I'm left only with the alternative of declaring createdUser outside the block, assigning it in the block, and then using it after.

在这种情况下,最佳做法是什么?

What is best practice in this instance?

推荐答案


似乎最好不要放置尝试正文中的多行业务逻辑

It seems to be best practice not to place multiple lines of business logic in the try body

实际上我会说是。您通常希望 catch 所有例外使用该值:

Actually I'd say it is. You usually want to catch all exceptions from working with the value:

try {
    const createdUser = await this.User.create(userInfo);

    console.log(createdUser)
    // business logic goes here
} catch (error) {
    console.error(error) // from creation or business logic
}

如果你只想从承诺中捕捉和处理错误,你有三种选择:

If you want to catch and handle errors only from the promise, you have three choices:


  • 将变量声明为外部,并根据是否存在异常进行分支。这可以采取各种形式,例如

  • Declare the variable outside, and branch depending on whether there was an exception or not. That can take various forms, like


  • catch 阻止

  • 提前返回或重新抛出来自 catch block

  • 设置一个标志, catch 块是否捕获到异常,并在中测试它,如果条件

  • 测试已分配的变量值

  • assign a default value to the variable in the catch block
  • return early or re-throw an exception from the catch block
  • set a flag whether the catch block caught an exception, and test for it in an if condition
  • test for the value of the variable to have been assigned

let createdUser; // or use `var` inside the block
try {
    createdUser = await this.User.create(userInfo);
} catch (error) {
    console.error(error) // from creation
}
if (createdUser) { // user was successfully created
    console.log(createdUser)
    // business logic goes here
}


  • 测试捕获的异常的类型,并根据它处理或重新抛出它。

  • Test the caught exception for its type, and handle or rethrow it based on that.

    try {
        const createdUser = await this.User.create(userInfo);
        // user was successfully created
        console.log(createdUser)
        // business logic goes here
    } catch (error) {
        if (error instanceof CreationError) {
            console.error(error) // from creation
        } else {
            throw error;
        }
    }
    

    不幸的是,标准JavaScript(仍然)没有语法支持条件异常

    Unfortunately, standard JavaScript (still) doesn't have syntax support for conditional exceptions.

    使用 然后有两个回调而不是尝试 / catch 。这实际上是最不丑陋的方式,也是我个人的建议,因为它的简单性和正确性,不依赖于标记错误或结果值的外观来区分履行的履行和拒绝:

    Use then with two callbacks instead of try/catch. This really is the least ugly way and my personal recommendation also for its simplicity and correctness, not relying on tagged errors or looks of the result value to distinguish between fulfillment and rejection of the promise:

    await this.User.create(userInfo).then(createdUser => {
        // user was successfully created
        console.log(createdUser)
        // business logic goes here
    }, error => {
        console.error(error) // from creation
    });
    

    当然它带有引入回调函数的缺点,这意味着你不能轻易 break / 继续循环或从外部函数返回返回 s。 / p>


  • Of course it comes with the drawback of introducing callback functions, meaning you cannot as easily break/continue loops or do early returns from the outer function.

    这篇关于正确尝试...使用Async / Await捕获语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆