skip to Main Content

I have this code (view on JSFiddle):

fetch('https://some.invalid.url').then(resp => resp.text())
.catch(err => console.log("got error: " + err))
.then(text => console.log("got text: " + text));

Currently this logs the two lines

"got error: TypeError: Failed to fetch"
"got text: undefined"

I would like it to only log the line

"got error: TypeError: Failed to fetch"

In other words, I would like the promise chain to end once the .catch is called and not go into the .then. How can I do this?

(I could throw an exception inside the .catch, but I think that results in a unhandledrejection event which is undesirable).

2

Answers


  1. Your issue is that your .catch() returns a resolved promise (resolving with the return value of console.log(), ie undefined).

    Either move the .catch() to the end of the promise chain

    fetch('https://some.invalid.url').then(resp => resp.text())
    .then(text => console.log("got text: " + text))
    .catch(err => console.log("got error: " + err));
    

    or have it continue rejecting the chain (but note this will throw an uncaught promise rejection error)

    fetch('https://some.invalid.url').then(resp => resp.text())
    .catch(err => {
      console.log("got error: " + err);
      return Promise.reject(err);
    })
    .then(text => console.log("got text: " + text));
    
    Login or Signup to reply.
  2. You need to swap the ordering so the .catch() is at the end of the chain.

    fetch('https://some.invalid.url').then(resp => resp.text())
    .then(text => console.log("got text should fail: " + text))
    .catch(err => console.log("got error should fail: " + err));
    
    
    fetch('https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js').then(resp => resp.text())
    .then(text => console.log("got text that should succeed: " + text))
    .catch(err => console.log("got error should succeed: " + err));
    

    (view on JSFiddle)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search