Search code examples
javascriptfetches6-promise

How to have 3 fetches in a javascript promise?


I'm having a bit of trouble figuring this out.

I have a fetch to wiki, but if that doesn't work, I want it to use a different link. Now if that doesn't work, I want it to send to a different link as the main default.

This is what I have right now which works great!

fetch(url)
.then(response => {
  if(response.ok){
    return response
  }

  else if (!response.ok) {
    return fetch(link + location)
  }
})

I'd appreciate any idea on how to add a third fetch. Thank you!


Solution

  • You can just chain it onto the end with another then:

    fetch(url)
        .then(response => {
            if (response.ok) return response;
            return fetch(link + location);
        })
        .then(response => {
            if (response.ok) return response;
            return fetch('whatever your third link is');
        });
    

    Of course, Jonas's answer is much cleaner because it avoids repetition and generalizes this operation to any number of fallback urls.