0

I'm trying to wrap my mind around the best way to tackle this. Ultimately, I'm trying to set this up to redirect if fetch doesn't work in like 5 seconds or so. I came up with this crude attempt so far. Thoughts?

const fetchData = fetch('https://swapi.devs/api/films').then(response=>response.json());
const timer= new Promise((resolve) => setTimeout(resolve, 5000, -1));

function init() {
    const promises = [fetchData, timer];
  Promise.any(promises).then(value => { 
    if (!value) {
        console.log('I got negative 1');
        // eventually do window.location.href = "https://www.example.com";
    } else {
        console.log(value);
    }
  });
}

init();

tlflow
  • 165
  • 1
  • 3
  • 10

1 Answers1

1

You can create an https://developer.mozilla.org/en-US/docs/Web/API/AbortController and pass it's signal in every fetch params, and use a setTimeout to abort it.

For a single promise it would looks like:

const controller = new AbortController();

const fetchResult = await fetch(fetchURL, { signal: controller.signal });

setTimeout(() => controller.abort(), timeoutDuration);

Sure you need to wrap it in a try/catch, and update it to work with Promise.all

Constantin
  • 3,655
  • 1
  • 14
  • 23