这等待抛出意外的令牌错误

this await throwing unexpected token error

我有一个简单的 async 函数。它只是发送一个请求和 returns 数据:

export const updatePanorama = async ({ commit }, payload) => {
  const urlEnd = '/v1/pano/update'
  const type = 'post'
  const resp = await api.asyncRequest(urlEnd, type, payload)
  commit('SET_PANORAMA', resp.data)
  return resp
}

这就是我使用函数的方式:

handleUpdatePanorama (panorama) {
  const payload = {}
  this.updatePanorama(payload).then(resp => {
    this.setIsLoading(false)
    this.handleAlert('updateSuccess', 'success')
  }).catch(() => {
    this.setIsLoading(false)
    this.handleAlert('updateError', 'danger')
  })
},

问题是,如果 then 中有错误,catch 之后的代码就会运行。但是这样我就不知道catch错误是请求错误还是then里面的代码触发的错误

我正在尝试 trycatch 来解决这个问题:

handleUpdatePanorama (panorama) {
  try {
    const payload = {}
    const resp = await this.updatePanorama(payload)
    console.log('resp:', resp)
    this.setIsLoading(false)
    this.handleAlert('updateSuccess', 'success')
  } catch (err) {
    this.setIsLoading(false)
    this.handleAlert('updateError', 'danger')
  })
},

但是,我在这一行中收到意外的令牌错误:await this.updatePanorama(payload)

我做错了什么?

The problem is, the code after catch runs if there's an error inside then

解决方案是不使用 catch,而是使用第二个 then 参数。查看 difference between .then(…).catch(…) and .then(…, …) 了解详情。

I'm trying try and catch to solve that problem

那行不通,如果 setIsLoadinghandleAlert.

抛出异常,catch 子句仍将被调用

I get an unexpected token error. What am I doing wrong?

您尚未将 handleUpdatePanorama 方法声明为 async

要缓解问题并修复语法,您可以编写

async handleUpdatePanorama (panorama) {
  var result
  try {
    const payload = {}
    const resp = await this.updatePanorama(payload)
    console.log('resp:', resp)
    result = ['updateSuccess', 'success']
  } catch (err) {
    result = ['updateError', 'danger']
  } finally {
    this.setIsLoading(false)
  }
  this.handleAlert(...result)
},

如果您需要专门处理来自 updatePanorama 的错误,请使用 .then(onSuccess, onError) 的第二个参数

handleUpdatePanorama(panorama) {
    const payload = {}
    this.updatePanorama(payload).then(resp => {
        this.setIsLoading(false)
        this.handleAlert('updateSuccess', 'success')
    }, err => {
        // handle error from updatePanorama
        // you can throw err if you also want to handle the error in .catch()
    }).catch(() => {
        this.setIsLoading(false)
        this.handleAlert('updateError', 'danger')
    })
}

注意:如果您从错误处理程序 return(或没有 return 语句),任何后续 .then(onSuccess 将执行,如果您抛出错误(或 return Promise.reject() 例如,.catch() 代码也将 运行