[Vuejs]-Promise: skip all fulfill and reject reactions but execute .finally

2πŸ‘

βœ…

Is it possible to skip all subsequent .then(...) and .catch(...) calls within one of such handlers to go directly to .finally()?

No.

Currenly I stop the chain by just infinitely waiting – yet this approach of pending Promise is an obstacle.

Indeed, don’t do that. You can skip then handlers by using rejections (exceptions) for flow control, but the more appropriate way is to handle this by nesting the part of the chain to be skipped inside an if statement.

This is done to handle certain API responses that have common response handling (like responses with code >= 500)

For that, you should use something like

return axios.request(endpoint).then(response => {
    …
}).catch(error => {
    if (api.handleCommonError(error)) return; // returns false if it couldn't handle the error
    …
}).finally(() => {
    …
});

Yes, you cannot hide this kind of error handling inside an api.request function.

πŸ‘€Bergi

1πŸ‘

You can use async and await. All modern browsers support them, and your bundler can make them compatible with older browsers.

For example:

async function request (endpoint) {
  try {
    const response = await axios.request(endpoint);
    return api.onSuccess(response);
  } catch (err) {
    api.onError(err);
  } finally {
    // Always executed, even if no error was thrown
  }
}

You can also do it more traditionally:

function request (endpoint) {
  return axios.request(endpoint).then(api.onSuccess, api.onError).then(() => {
    // Code is always executed after error / success
  }
}
πŸ‘€coyotte508

Leave a comment