Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 655
Hakim Avatar asked Oct 20 '25 01:10

Hakim


1 Answers

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));
like image 190
William Lepinski Avatar answered Oct 22 '25 06:10

William Lepinski