How to retry a failed promise in Javascript?

The problem:

When a promise fails, we want to handle it by retrying it's request. We solve it by using recursion. We need to implement 2 functions. The first would be the delay function, the other would be the promise function

Delay function:

function wait(t) {
    return new Promise((resolve) => setTimeout(resolve, t * 1000));
  }

Promise function

const promise = (tries, delay) => {
    function onError(err) {
      tried = tries - 1;
      if (!tried) {
        throw err;
      }
      return wait(t).then(() => promise(tries, delay));
    }
    return promise.catch(onError);
  };

Get the result by simply calling like this:

promise(5, 5).then(result => console.log(result))

Comments

Popular posts from this blog

Support for the experimental syntax 'decorators' isn't currently enabled (5:3):

How to add environment variables into Heroku container

Running CQL scripts in Cassandra