【问题标题】:Try/catch a promise or just catch?尝试/抓住一个承诺或只是抓住?
【发布时间】:2022-01-13 11:55:58
【问题描述】:

this.$auth.loginWith 返回一个 Promise,但我不确定是否应该将它包装在 try/catch 中,或者只是在 Promise 上使用 catch。

哪种方法是正确的?

尝试/捕捉:

async login() {
            try {
                const response = await this.$auth.loginWith('laravelSanctum', {
                    data: {
                        email: 'xxx',
                        password: 'xxx',
                    },
                });

                this.$auth.setUser(response.data.data);
            } catch (e) {

            }
        },

赶上:

async login() {
                const response = await this.$auth.loginWith('laravelSanctum', {
                    data: {
                        email: 'xxx',
                        password: 'xxx',
                    },
                }).catch(function(e) {
                });

                this.$auth.setUser(response.data.data);
        },

【问题讨论】:

  • 到目前为止,您为自己找到答案做了什么? -> How much research effort is expected of Stack Overflow users?
  • 它们做了两件不同的事情。他们不必这样做,但按照您编写它们的方式,第一段代码将不会在失败时调用this.$auth.setUser();。第二段代码会将undefined 分配给response(因为.catch() 不返回任何内容),并且this.$auth.setUser(response.data.data); 将 被调用。然后失败,因为response 是undefined,因此response.data 会抛出错误。
  • 不要这样做。忽略错误不是一个好习惯,如果你真的有理由至少添加评论为什么要这样做。

标签: javascript nuxt.js nuxt-auth


【解决方案1】:

一般而言,最佳实践不将async/await 与使用promise 方法(.then、.catch)结合使用,因此您的try/catch通常会是这两个选项中更好的选择。

@VLAZ put his finger on 的一个很好的理由是:当你混合这样的隐喻时,阅读流程可能会很棘手,在你的情况下,使用 .catch 的版本实际上会导致错误,因为你的具体catch 处理程序使用undefined 将拒绝转换为履行,因此代码在await 之后继续,并在response 为undefined 时尝试执行this.$auth.setUser(response.data.data);,从而导致似乎与登录无关的新错误。


但通常情况下,更好的是not handle the rejection at all,以便调用者知道登录是否有效(因为如果出现错误,login 将拒绝)。但是对于代码的入口点(事件处理程序,诸如此类),拒绝的内联处理可以占有一席之地。这取决于如何使用login。除了入口点,默认让错误/拒绝传播给调用者。

【讨论】:

    猜你喜欢
    • 2016-10-25
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多