Is there a way of jumping from a then callback directly into the catch callback inside a JavaScript Promise 'then-chain'?
So by example I am checking the data from a fetch call:
fetch('api')
  .then(response => {
      if (response.json() === null) {
         // error
         // call catch
      }
      else {
       return response.json();
      }
  })
  .then(data => console.log(data.message))
  .catch(error => console.log(error));
Are there any best practices or workarounds?
You can call Promise.reject with the error. You'll receive the error inside the catch() method.
fetch('api')
    .then(response => {
        if (response.json() === null) {
            return Promise.reject('Somethind bad happened');
        }
        else {
            return response.json();
        }
    })
    .then(data => console.log(data.message))
    .catch(error => console.log(error));
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With