简体   繁体   English

尝试/抓住 promise 还是抓住?

[英]Try/catch a promise or just catch?

this.$auth.loginWith returns a promise, but I am unsure if I should wrap it in a try/catch or just use a catch on the promise. this.$auth.loginWith返回一个 promise,但我不确定是否应该将它包装在 try/catch 中,或者只是在 promise 上使用catch

Which is the correct way?哪个是正确的方法?

Try/Catch:试着抓:

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

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

            }
        },

Catch:抓住:

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

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

In general, it's best practice not to combine async / await with using the promise methods ( .then , .catch ), so your try / catch would usually be the better of those two options.一般来说,最好不要async / await与使用 promise 方法( .then.catch )结合起来,因此您的try / catch通常会比这两个选项更好。

And @VLAZ put his finger on one of the good reasons for that: When you mix metaphors like that, it can be tricky to read the flow, and in your case the version using .catch will actually cause an error because the your specific catch handler converts rejection to fulfullment with undefined , so the code continues after the await , and tries to do this.$auth.setUser(response.data.data); @VLAZ 指出了其中一个很好的理由:当你混合这样的隐喻时,阅读流程可能会很棘手,在你的情况下,使用.catch的版本实际上会导致错误,因为你的特定catch处理程序使用undefined将拒绝转换为履行,因此代码在await之后继续,并尝试执行this.$auth.setUser(response.data.data); when response`` is undefined`, causing a new error that seems unrelated to login.response`` is未定义时,会导致一个似乎与登录无关的新错误。


But normally, even better is to not handle the rejection at all so that the caller knows whether the login worked or not (because login will reject if there was an error).但通常情况下,更好的是根本不处理拒绝,以便调用者知道登录是否有效(因为如果出现错误login将拒绝)。 But for entry points into your code (event handlers, that kind of thing), inline handling of rejections can have a place.但是对于代码的入口点(事件处理程序,诸如此类的东西),拒绝的内联处理可以占有一席之地。 It depends on how login is used.这取决于如何使用login Other than entry points, default to letting the error/rejection propagate to the caller.除了入口点,默认让错误/拒绝传播给调用者。

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

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