How to implement request retry mechanism in JavaScript (simple & reusable)

Osama (Oisee) Ishtiaq
2 min readApr 15, 2022

Hi 👋🏼,

If you are working with 3rd party/external apis that occasionally go down for brief periods of time or just drop your http requests once in a while, it would be a good idea to implement retry mechanism for your requests. To keep it short, below is the JavaScript code for implementing retry and after that, a code example with comments explaining how to use it. :)

And then all you have to do is wrap your requests with this function, provide an error handler and an optional `retryCount` which by default is 3 so by default, your requests will be retried 3 times before it fails and calls the error handler function. In below code snippet, first function is an example of existing code without any retry logic and second function showcases how you can change it to use retry.

Note: please do keep in mind that most of the times you don’t want to reinvent the wheel and using the builtin retry mechanism of which ever http library you are using would be sufficient. But this example doesn’t only cover http requests, you can basically use this wrapper function for any piece of code that might potentially fail and needs multiple retries. ;-)

So, to summarise, for making any request use the retry mechanism, all you have to do is follow 3 steps:
1. wrap your code in requestWithRetry method
2. copy the code in try block and paste as 1st argument
3. copy the code in catch block and paste as 2nd argument
And voila!

Leave a comment if you have any questions or if you find any bugs in the code. Happy Coding! 🧑🏻‍💻

--

--

Osama (Oisee) Ishtiaq

Started programming when I was a kid and never looked back. I write about really specific things that I encounter in my daily dev life.