I have a simple async
function. It just sends a request and returns the data:
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
}
And this is how I'm using the function:
handleUpdatePanorama (panorama) {
const payload = {}
this.updatePanorama(payload).then(resp => {
this.setIsLoading(false)
this.handleAlert('updateSuccess', 'success')
}).catch(() => {
this.setIsLoading(false)
this.handleAlert('updateError', 'danger')
})
},
The problem is, the code after catch
runs if there's an error inside then
. But this way I don't know whether the catch error is an request error or and error triggered by the code inside then.
I'm trying try
and catch
to solve that problem:
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')
})
},
However, I get an unexpected token error in this line: await this.updatePanorama(payload)
What am I doing wrong?
The solution for that is to not use
catch
, but the secondthen
parameter. Have a look at the difference between.then(…).catch(…)
and.then(…, …)
for details.That won't work, the
catch
clause will still be called if there's an exception thrown bysetIsLoading
orhandleAlert
.You have not declared the
handleUpdatePanorama
method asasync
.To mitigate the issues and fix the syntax, you could write