简体   繁体   English

尝试在Vuejs中使用async / await捕获

[英]Try catch with async / await in Vuejs

I am using VueJS/Nuxt and Vuex store, and I have the following method defined: 我正在使用VueJS / Nuxt和Vuex存储,并且定义了以下方法:

async UpdateData () {
  try {
    await this.$store.dispatch('updateMyData', this.data)
    successMsg({ message: 'Data updated successfully' })
  } catch (e) {
    errorMsg({ message: 'Some error' })
  }
}

The problem is that I have not yet created the action 'updateMyData', so in my console I see the error '[vuex] unknown action type: updateMyData' 问题是我尚未创建动作'updateMyData',因此在控制台中我看到错误'[vuex] unknown action type: updateMyData'

However, still the successMsg() is executed and I get the message 'Data updated successfully'. 但是,仍然执行了successMsg()并且得到了消息“数据更新成功”。

My assumption was that if await... fails, it will go to the catch block. 我的假设是,如果await ...失败,它将进入catch块。

Can you please help with what is wrong with my code and how I can correct it. 您能帮我解决我的代码的问题以及如何纠正它。

That error is not an actual promise error, it's a warning from Vuex, saying that the 'updateMyData' action hasn't been registered anywhere in your Vuex store. 该错误不是实际的承诺错误,而是来自Vuex的警告,说'updateMyData'操作尚未在Vuex存储中的任何位置注册。 The message comes from a simple console.log(/error/warn) instead of a throw or reject() , which is why it doesn't fail in your function here. 该消息来自简单的console.log(/ error / warn)而不是throwreject() ,这就是为什么它不会在这里的函数中失败的原因。

In the case of an await expression not returning a Promise object, it turns what is passed in into a "resolved promise". 在await表达式不返回Promise对象的情况下,它将传递的内容转换为“已解决的承诺”。 This simply means your undefined function is returned immediately as if it Resolved. 这仅表示您未定义的函数将立即返回,就像已解决一样。 Hence, it doesn't reject and the await doesn't throw. 因此,它不会拒绝并且await不会抛出。

If the value of the expression following the await operator is not a Promise, it's converted to a resolved Promise. 如果await运算符后面的表达式的值不是Promise,则会将其转换为解析的Promise。

This comes from here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await#Description 这来自这里: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await#Description

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

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