skip to Main Content

I use axios to connect to a Telegram bot to get new messages every second. Occasionally I get axios connection error. The problem is that this breaks the setTimeOut(). I was warned of this when using this method but it was fine for testing. I am working towards production now so I need something more robust but simple.

One suggestion given was use a cron job but this is not an option on the server.

Is there a better way for this code to just accept the error and continue on that wont leads to other issues?

getAPI(apiName) {
 return axios.get(`${this.getApiURL()}/${apiName}`);
}

getApiURL() {
  return `https://api.telegram.org/bot${this.getToken()}`;
}

getUpdates() {
     this.getAPI('getUpdates')
         .then(res => {
             this.storeUpdates(res.data);
             setTimeout(() => {
                 this.getUpdates();
             }, 1000);
         })
         .catch(err => {
             console.log('::: ERROR :::', err);
         });
 }

2

Answers


  1. Why not use setInterval() instead if all you want is to check for an update every one second? This way throwing an error will not break your interval ao long as you’re handling it correctly.

    Login or Signup to reply.
  2. You can opt one of these two:

    1. use setInterval with getUpdates as the task. With this however, Yo need to consider the right timing, in such a way that getUpdates() completes before interval time expires.

    2. use setTimeout in both promise resolve and reject. When API returns data, use a little bit longer timeout period than when error is encountered. This ensures API is called x mills after every success call, and y mills after error is encountered

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search