Guide on implementing retry functionality in JavaScript/Ajax

I am starting out with Javascript and Ajax, and I need to implement a retry mechanism that tries 3 times if the ajax response is not 200.

Ajax Function -

function fireAndForget(strURL) {
    log("will attempt to invoke... [ " + strURL + " ]");
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    } // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
    }
    self.xmlHttpReq.open('GET', strURL, true);
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            if(self.xmlHttpReq.status == 200) {
                log("received JSON response : [" + self.xmlHttpReq.responseText + "]");
                var resObj = parseJSON(self.xmlHttpReq.responseText);
                if("handled" in resObj) {
                    if(resObj.handled) {
                        if("success" in resObj) {
                            if(resObj.success) {
                                // DO NOTHING
                            } else {
                                if(resObj.message) {
                                    alert(resObj.message);
                                }
                            }
                        }
                    }
                } else {
                    log("auth update notification was not handled. response : [" + self.xmlHttpReq.responseText + "]");
                }
            } else {
                // unable to contact the auth update listener
                alert("<%=pNotifyFailedMsg%>");
                log("unable to contact listener URL @ [" + strURL + "]");
            }
        }
    };
    // fire a get request with the SSO information
    self.xmlHttpReq.send(null);
    //alert("sent url : [" + strURL +"]");
}

Need to include retry logic for

if(self.xmlHttpReq.status == 200) {
        log("received JSON response : [" + self.xmlHttpReq.responseText + "]");
        var resObj = parseJSON(self.xmlHttpReq.responseText);
        if("handled" in resObj) {
            if(resObj.handled) {
                if("success" in resObj) {
                    if(resObj.success) {
                        // DO NOTHING
                    } else {
                        if(resObj.message) {
                            alert(resObj.message);
                        }
                    }
                }
            }
        } else {
            log("auth update notification was not handled. response : [" + self.xmlHttpReq.responseText + "]");
        }
    } else {
        // unable to contact the auth update listener
        alert("<%=pNotifyFailedMsg%>");
        log("unable to contact listener URL @ [" + strURL + "]");
    }

I have tried using loops and other solutions in the else part of the above code, but it didn't work. Can someone please provide guidance on the best approach for implementing a retry in such cases?

The alert in the else part should only be shown after 3 retry attempts.

Answer №1

Assuming that makeRequest refers to the function explained in detail here, if you require traditional JavaScript, you can convert ES6 code like const x = (a,b=0)=>(c)=>22 to

function x(a,b){if(b===undefined){b=0} return function(c){...

An example of a retry builder function could be structured as follows:

const createRetry = (
  maxRetries, //number of attempts
  passingResults = (id) => id, //function for passing results
  tries = 0, //number of previous attempts
) => (method, url) =>
  makeRequest(method, url)
    .then(passingResults)
    .catch(
      (error) =>
        tries < maxRetries
          ? createRetry(//recursive call upon failure
              maxRetries,
              tries + 1,//increment tries by one after current attempt
              passingResults,
            )(method, url)
          : Promise.reject(error),//maximum retries reached, reject promise
    );

const retryTwiceAndNameIsInResponse = createRetry(
  2, //retry twice
  //function to check if xhr json result contains a 'name' property
  //passing and returning the result if it does, else rejecting with an error
  //an optional function can be passed, defaulting to an id function if not provided
  (result) =>
    result.name
      ? result
      : Promise.reject(new Error('no name in result')),
);
//tries defaults to 0, indicating the number of attempts made to get the correct result

//example usage:
retryTwiceAndNameIsInResponse(method,url)
.then(response=>console.log('Success, response:',response))
.catch(error=>console.log('Failed:',error))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The function res.getHeader is not recognized within the Next.js API environment

I am currently working on a web application using NextJS 13, TypeScript, Next Auth v4, Prisma (using SQLite for development), and OpenAI. While accessing the API endpoint, I encountered an error in the console with the following message: error - TypeError ...

The entire DOM refreshes when a user updates the input field

In my React component, I am managing two states: inputText and students. The inputText state tracks the value of an input field, while the students state is an array used to populate a list of student names. The issue arises when the inputText state change ...

Display a new div with its content every 5th item

I am currently working with a Smarty template that contains the following code output: Check out my other question on Stackoverflow My problem lies in the fact that the provided code does not repeat the inserted HTML after every 5 elements... Could some ...

"Looking to retrieve data from an array instead of an object in JavaScript? Here's how you can

There is a slight issue with my fetch method in grabbing data from this link . I am attempting to use the .map function on it but instead of functioning properly, I encounter an error that says Unhandled Rejection (TypeError): jedis.map is not a function. ...

How to Make WebService Calls in JavaScript in ASP.NET without ScriptManager

I developed a Web service for my Asp.net project. Right now, I am accessing the service through JavaScript by including the Service in ScriptManager. However, I am looking to eliminate the need for a ScriptManager so that I can utilize it on any HTML pag ...

ESLint flagging "Unexpected tab character" error with "tab" indentation rule enabled

Currently, my ESLint setup includes the Airbnb plugin (eslint-config-airbnb) along with the Babel parser. I recently decided to enforce the rule of using Tab characters for indentation instead of spaces. This is how my .eslintrc file looks like: { "p ...

Retrieve data from Ajax request

Sorry if this is a silly question, but I'm interested in making an ajax call and utilizing the result in R. The following call is from www.randomuser.me: $.ajax({ url: 'https://randomuser.me/api/?format=csv?results=5000', dataType: &apo ...

Utilizing JQuery to differentiate a single element within a group of elements

As a beginner in the world of jquery, I am attempting to assign a font awesome icon star (fa-star) to differentiate between admins and regular members within the group members bar. The usernames have been blurred out for privacy reasons, but my goal is to ...

What methods can be used to conceal a div when the content is not being shown?

I'm a beginner in HTML and CSS and I have a page with the following code: Content displayed : <div id="row-3" ><!-- Row 3 starts here --> <div class="groupz_column1" style="margin-right:0px;"><a href="http://www.xyz.in/ads/ ...

How can I click the add button to show the information in the input field and display it in a <p> tag that is created using JavaScript? (without using inline JavaScript)

Is there a way to dynamically add user input to the page without using inline JavaScript and with minimal HTML? I want to create a new paragraph element through JavaScript when the user clicks a button, instead of relying on static elements in the HTML. & ...

Designing a carousel-style menu list with navigation buttons for moving forward and backward

I'm running into some trouble while attempting to create a carousel. Firstly, the issue I am facing is that when you continuously click on the Next button, the function keeps working even after reaching the last item. I'm not sure how to make th ...

Creating a CSS animation to slide a div outside of its container is

I currently have a flexbox set up with two adjacent divs labeled as DIV 1 and DIV 2. By default, both DIV 1 and DIV 2 are visible. DIV 2 has a fixed width, occupying around 40% of the container's width. DIV 1 dynamically adjusts its width to ac ...

Expand Elements to occupy entire width

My CSS skills are still in the early stages. I haven't delved too deeply into it. I have a query regarding how to achieve full width for an element. I've included my code below, but the basic approach I tried using 'width: 100%' didn&a ...

Efficient method for handling numerous AJAX requests

I have a web application that currently makes 14-15 AJAX calls to various APIs. The issue is that the combined time it takes for all the AJAX calls to complete is significantly longer than when I individually type each API's URL into the browser. Cur ...

Updating a value within destructuring and a loop: A step-by-step guide

My Goal: I aim to modify a value in an object that is part of an array element. Take a look at the code snippet below for a clearer understanding. An issue arises when I update the object's value through reference instead of creating a new copy, cau ...

Extract the value from JSON data

I am faced with the challenge of extracting the value of slug from each child in a JSON dataset. The issue lies in the fact that I cannot predict how many children will be generated whenever new data is received. The generation of nested children is dynam ...

Custom providers do not override Angular UrlResolver

In my Angular application, I am trying to implement a custom UrlResolver provider to incorporate cache breaking logic. I came across this question on Stack Overflow: . Unfortunately, it seems that overriding the default compiler UrlResolver using a provid ...

React-hook-form does not display the input length in a custom React component

Introducing a custom Textarea component designed for reusability, this basic textarea includes a maxlength prop allowing users to set the maximum input length. It also displays the current input length in the format current input length/max length. While ...

Is it possible to reposition the vertical scrollbar to a location that is not on the left or right side?

Whenever I resize my modal on small screens, a horizontal scrollbar appears, causing the vertical scrollbar to disappear as it gets stuck on the right side. I am looking for a solution to keep the vertical scrollbar on the right side of the modal while scr ...

Steps for Updating Jquery Mobile Listview Following an Ajax Request

I am currently facing an issue with refreshing the listview in Jquery Mobile after pulling Ajax content into a div. The problem specifically arises when the Ajax content is loaded into a listview within a collapsible content block. Below is the HTML snip ...