Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS: Request Loop Until Status Code 200

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');
    }
});
like image 612
emarel Avatar asked Feb 03 '16 19:02

emarel


Video Answer


2 Answers

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 ^^

like image 63
crackmigg Avatar answered Oct 16 '22 23:10

crackmigg


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.

like image 40
Axelfoley Avatar answered Oct 17 '22 00:10

Axelfoley