Home > OS >  How to repeat the same Promise in NodeJS with an Array input until it resolves or the Array ends?
How to repeat the same Promise in NodeJS with an Array input until it resolves or the Array ends?

Time:09-23

I have an array of URLs for the same audio file which are not always working due to server loads. So, whenever a URL is needed, I should check first the headers of the first URL to make sure it's working now. If it's not working, I check the next URL.. and so on until the array ends.

My question is: How to chain a recurring of the same Promise (different URL each time) with the ability to break the chain once a working URL is found?

CodePudding user response:

While a recursive Promise-returning function would be simple enough...

const getWorkingAudio = (i = 0) => {
  if (i === urls.length) {
    throw new Error('All URLs bad');
  }
  return fetch(urls[i])
    .then(validateHeaders)
    .catch((error) => {
      return getWorkingAudio(i   1);
    });
};
getWorkingAudio()
  .then(handleSuccess)
  .catch(handleError);

It's a pretty bad sign if you often have so many URLs that may be bad due to server load - better to fix/improve the server than to have developers have to work on silly workarounds like this.

CodePudding user response:

  • Related