Having some asynchronous code that needs to halt in case of error but continues to execute:
async saveCoupons({ state, rootState, dispatch, commit }) {
const promises = []
state.userCoupons.forEach(coupon => {
if (coupon.isNew && coupon.isUpdated) {
// if the user is creating a new coupon
promises.push(Vue.axios.post('/api_producer/coupons.json', coupon, { params: { token: coupon.token } }))
} else if (!coupon.isNew && coupon.isUpdated) {
// if the user is updating the coupon
promises.push(Vue.axios.patch(`api_producer/coupons/${coupon.id}/`, coupon, { params: { token: coupon.token } }))
}
})
try {
await Promise.all(promises)
dispatch('utilities/showModal', 'success', { root: true })
dispatch('fetchProducerCoupons')
} catch (err) {
let couponToken = err.request.responseURL.split('token=')[1]
commit('ADD_ERROR_ON_COUPON', couponToken)
console.log(err)
}
}
The current structure of the code functions, but it appears inefficient. The objective is to halt the execution of
dispatch('utilities/showModal', 'success', { root: true })
dispatch('fetchProducerCoupons')
If any of the API calls encounter an error. It is preferable to catch the error within the forEach loop to immediately access and handle the item rather than postponing it for later (as done with
{ params: { token: coupon.token } }
.