Skip to content Skip to sidebar Skip to footer

Promise Continues After Error

I have some async code that needs to stop in case of error but keeps executing: async saveCoupons({ state, rootState, dispatch, commit }) { const promises = [] state.userCo

Solution 1:

I think the best way would be to wrap the Vue.axios requests into your own Promise. Then, if the requests fail, you have the coupon tokens in your error.

Something like

const promises = [];

promises.push(
  Vue.axios.post('/api_producer/coupons.json', coupon)
    .catch(() => { throw new Error(coupon.token) }));
    
Promise.all(promises).catch(tokens => {
  tokens.forEach(token => {
    // Commit/handle errorous token
  });
});

Solution 2:

You can wrap your api call in another promise and check the status. Something like this:

promises.push(

  new Promise((resolve, reject) => {

    Vue.axios.post('/api_producer/coupons.json', coupon, { params: { token: coupon.token } })
    .then((response) => {
      if (response.status !== 200) {
        coupon.error = true;
        reject();
      } else {
        resolve();
      }
    });

  })
);

The reject will keep these two lines from being executed:

  dispatch('utilities/showModal', 'success', { root: true })
  dispatch('fetchProducerCoupons')  

Solution 3:

Thanks to Moritz Schmitz v. Hülst & sklingler93 for the help, I restructured the code and it's working.

I'm wondering if there's a way to write all of this using only async/await... If anybody has an idea, would love to see it :)

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(new Promise((resolve, reject) => {
                Vue.axios.post('/api_producer/coupons.json', coupon)
                    .then(response => resolve(response))
                    .catch(err => {
                        reject(err)
                        commit('ADD_ERROR_ON_COUPON', coupon.token)
                    })                        
            }))
        } else if (!coupon.isNew && coupon.isUpdated) {
            // if the user is updating the coupon
            promises.push(new Promise((resolve, reject) => {
                Vue.axios.patch(`api_producer/coupons/${coupon.id}/`, coupon)
                    .then(response => resolve(response))
                    .catch(err => {
                        reject(err)
                        commit('ADD_ERROR_ON_COUPON', coupon.token)
                    })
            }))
        }
    })
    Promise.all(promises)
        .then(() => {
            dispatch('utilities/showModal', 'success', { root: true })
            dispatch('fetchProducerCoupons')
        })
        .catch(err => console.error(err))
},

Post a Comment for "Promise Continues After Error"