0

私は簡単な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')
  })
},

catch問題は、内部にエラーがある場合に実行されるコードthenです。しかし、この方法では、キャッチエラーがリクエストエラーなのか、それとも内部のコードによってトリガーされたエラーなのかわかりません。

私はその問題を解決しようtryとしています:catch

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)

私は何を間違っていますか?

4

2 に答える 2

1

catch問題は、内部にエラーがある場合、実行後のコードですthen

その解決策は、を使用せずcatch、2 番目のthenパラメーターを使用することです。詳細については、と違い.then(…).catch(…).then(…, …)を参照してください。

私はその問題を解決しようtryとしていますcatch

またはcatchによって例外がスローされた場合でも、句は呼び出されます。setIsLoadinghandleAlert

予期しないトークン エラーが発生します。私は何を間違っていますか?

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)
},
于 2016-12-19T02:50:36.383 に答える
1

特に updatePanorama からのエラーを処理する必要がある場合は、2 番目の引数を .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()コードも実行されます

于 2016-12-19T02:56:22.383 に答える