2016-12-19 8 views
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') 
    }) 
}, 

then内部エラーがあるかどう問題が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)

は私が間違って何をしているのですか?

+0

関数が 'async'以外の場合、awaitは使用できません。 –

+0

FYI、' async/await'はES7の一部ではありません。 –

答えて

1

問題がthen

内部エラーがあるかどうそのための解決策がcatchが、2番目のthenパラメータを使用しないことです、catch実行後のコードです。詳細はdifference between .then(…).catch(…) and .then(…, …)をご覧ください。

私は動作しません、その問題

を解決するためにtrycatchをしようとしているsetIsLoadinghandleAlertによってスローされた例外があるかどう、catch句はまだ呼び出されます。

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

handleUpdatePanoramaメソッドをasyncと宣言していません。

問題を軽減し、構文を修正するには、あなたがupdatePanoramaから、具体的なエラーを処理する必要がある場合、あなたは(するonSuccess、onErrorメソッド)を.thenするために、第2引数を使用し、

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) 
}, 
+0

彼らは、2番目のパラメータを使用すると、反パターンと言いますか? – alex

+0

'彼らは何を言っているのか常に分かっているわけではありません:p - その用途を持っています –

+0

@alex誰が*彼ら*ですか?いいえ、この(他のユースケースでは望ましくない)振る舞いを*求めたいときは反パターンではありません。 – Bergi

1

を書くことができ

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文がない場合)、エラーがスローされた場合(またはPromise.reject()を返した場合など)、.then(onSuccessが実行され、.catch実行

関連する問題