When you don’t have an interface for knowing when a remote resource is available, an option to consider is to use exponential backoff rather than to poll that resource until you get a response.

Image for post

Set Up

In this scenario, let’s mimic the behaviour of a browser and a server. Let’s say the server has an abysmal failure rate of 80%.

const randomlyFail = (resolve, reject) =>
  Math.random() < 0.8 ? reject() : resolve();

const apiCall = () =>
  new Promise((...args) => setTimeout(() => randomlyFail(...args), 1000));

The apiCall function mimics the behaviour of calling an endpoint on a server.

Retrying

When the apiCall is rejected, getResource is called again immediately.

const getResource = () => apiCall().catch(getResource);

With a Delay

If a server is already failing, it may not be wise to overwhelm it with requests. Adding a delay to the system can be a provisional solution to the problem. If possible, it would be better to investigate the cause of the server failing.

const delay = () => new Promise(resolve => setTimeout(resolve, 1000));

const getResource = () =>
  apiCall().catch(() => delay().then(() => getResource()));

#javascript #exponential-backoff #asynchronous-programming #retry #promises #programming

Retrying and Exponential Backoff With Promises
3.60 GEEK