DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 963,274 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Abhinav Sachdeva
Abhinav Sachdeva

Posted on • Updated on

API Calls with retries

Have you run into a situation when you needed to call a buggy API that responds with an error ever so often?
What's the solution if you have no control over that API?

Retries to the rescue!

As it happens...

  1. Our fetchDataWithRetries function takes in the maxReties (uses 3 as a default value)
  2. When called, this function returns a function and we make use of closure to capture the value of tries and maxTries
  3. The returned function - apicall - takes in the URL to be called.
    1. If the response is a success - return it as is
    2. If there's an error increment the tries, check for max retry limit and recursively call itself

    const fetch = require('node-fetch');

    function fetchDataWithRetries(maxTries) {
        maxTries = parseInt(maxTries);
        if(!maxTries) maxTries =  3;
        let tries =  0;
            return function apicall(url) {
                if (!url) return Promise.reject("URL required")
                console.log("APICALL " + (tries + 1));
                return fetch(url)
                    .then(function (res) {
                        console.log("fetch success");
                        return res.json();
                    })
                    .catch(e => {
                        console.log("Fetch Error")
                        if (++tries < maxTries)
                            return apicall(url);
                        return Promise.reject(e)
                    });
            }
   }

 const  retyCount = 2, APIURL = 'https://jsonplaceholder.typicode.com/users/1';

fetchDataWithRetries(retyCount)(APIURL)
    .then(data => console.log(data))
    .catch(err => console.log(err));
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
leandroandrade profile image
Leandro Andrade

Great simple explanation, just add "url" when run "apicall" in catch fetch.

Collapse
 
abhinavsachdeva profile image
Abhinav Sachdeva Author

Thanks for the read. Updated.

This post blew up on DEV in 2020:

js visualized

๐Ÿš€โš™๏ธ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! ๐Ÿฅณ

Happy coding!