6

I currently have working code that does a request and checks if it receives a successful status code of 200. I would like to grow on this and loop it where it will keep sending requests until the status code is 200. I tried using a while loop but was not receiving the correct results. Thanks for the help!

request('http://0.0.0.0:9200', function (error, response, body) {
    if (!error && response.statusCode == 200) {
      console.log('success');
      do(something);
    }
    else {
      console.log('fail');
    }
});
1
  • Could wrap the request in a function, then have it call itself on the fail condition? Commented Feb 3, 2016 at 19:22

2 Answers 2

13

Would be something like:

let retry = (function() {
  let count = 0;

  return function(max, timeout, next) {
    request('http://0.0.0.0:9200', function (error, response, body) {
      if (error || response.statusCode !== 200) {
        console.log('fail');

        if (count++ < max) {
          return setTimeout(function() {
            retry(max, timeout, next);
          }, timeout);
        } else {
          return next(new Error('max retries reached'));
        }
      }

      console.log('success');
      next(null, body);
    });
  }
})();

retry(20, 1000, function(err, body) {
    do(something);
});

You can set a max number of retries and a timeout between retries. So that you do not introduce an infinite loop, and you do not deliver the final punch to an overloaded request target ^^

Sign up to request clarification or add additional context in comments.

4 Comments

would you mind explaining how this functionality works. I have implemented it but understanding is still a bit fuzzy.
What exactly do you not understand?
this works but request is deprecated, can you post an update with axios pretty please?
@scavenger its not 2016 anymore and we have observables that have retry operator, you can check retry ref official doc even takes this as their example. Also if you are using axios you should probably check out axios-retry.
2

I wanted a little more intuitive answer including promises. I build on top of miggs answer within a try/catch the code below with promises and axios.

Based on a simple example of recursive functions

const throwNumbers = (count = 0) => {
  console.log(count);
  if (count++ < 10) {
    throwNumbers(count);
  } else {
    console.log('max reached');
  };
};

You can put anything else on the try part and handle error codes in the catch part. You have to set a max number of retries, which is 10 in my case.

let getResponse = async(count = 0) => {
  try {
    const axiosResponse = await axios.get(someURL, {
      params: {
        parameter1: parameter1,
      },
    });
    return axiosResponse;
  } catch (error) {
    if (error || error.status != 200) {
      console.error('failed, retry');

      if (count++ < 10) {
        return getResponse(count);
      } else {
        throw new Error('max retries reached');
      };
    } else {
      throw error;
    };
  };
};

You would call the function with the following and handle the body or whatever with the response value.

let response = await getResponse();
console.log('This is the response:', response);

Has no timeout but works for me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.