Search code examples
javascriptasynchronouses6-promise

Promises invoke `catch` from within `then`


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?


Solution

  • 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));