【问题标题】:this await throwing unexpected token error这等待抛出意外的令牌错误
【发布时间】:2016-12-19 15:15:51
【问题描述】:

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

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错误是请求错误还是内部代码触发的错误。

我正在尝试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)

我做错了什么?

【问题讨论】:

  • 不能使用await,除非函数是async
  • 仅供参考,async/await 不是 ES7 的一部分。

标签: javascript async-await ecmascript-2017


【解决方案1】:

问题是,如果then 内部有错误,catch 之后的代码会运行

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

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

这不行,如果setIsLoadinghandleAlert 抛出异常,catch 子句仍然会被调用。

我收到意外的令牌错误。我做错了什么?

您尚未将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)
},

【讨论】:

  • 他们说使用第二个 then 参数是一种反模式?
  • They 并不总是知道they 在说什么:p - 它有它的用途
  • @alex 他们是谁?不,当您想要这种(在其他用例中不受欢迎的)行为时,它不是反模式。
  • @Bergi 我指的是互联网——好吧,也许你是对的。
  • @alex 嘿,我是这里的互联网! :-P
【解决方案2】:

如果您需要专门处理来自 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 都将执行,如果您抛出错误(或返回 Promise.reject() 例如,那么 .catch () 代码也会运行

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-15
    • 2019-08-09
    • 2019-09-26
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    相关资源
    最近更新 更多