如何在javascript / Ajax中添加重试

时间:2019-01-30 08:29:49

标签: javascript ajax

我是javascript和Ajax的新手,如果ajax响应不是200,则需要重试3次。

Ajax函数-

function fireAndForget(strURL) {
    log("will try 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 +"]");
}

需要在

上添加重试
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 + "]");
    }

在上面代码的其他部分,我尝试使用循环和其他解决方案,但没有用,请帮忙。 在这种情况下重试的好方法是什么

仅在3次重试后才显示警报(其他部分)

1 个答案:

答案 0 :(得分:1)

我假设makeRequesthere中描述的功能,如果您需要经典的JS,则可以将const x = (a,b=0)=>(c)=>22之类的ES6转换为function x(a,b){if(b===undefined){b=0} return function(c){...

您的重试生成器功能可能看起来像这样:

const createRetry = (
  maxRetries, //how many times to try
  passingResults = (id) => id, //function to "pass the result"
  tries = 0, //how many times tried
) => (method, url) =>
  makeRequest(method, url)
    .then(passingResults)
    .catch(
      (error) =>
        tries < maxRetries
          ? createRetry(//call itself again when it failed
              maxRetries,
              tries + 1,//add one to tries as we've just tried
              passingResults,
            )(method, url)
          : Promise.reject(error),//tried max tries times, just reject
    );

const retryTwiceAndNameIsInResponse = createRetry(
  2, //retry twice
  //function to check the xhr json result, if result has a name
  //  property then it passes and just returns the result,
  //  if not then it will reject the promise with an error
  //  a function can be optionally passed, if it's not passed
  //  then it will default to an id function (just returns what it gets)
  (result) =>
    result.name
      ? result
      : Promise.reject(new Error('no name in result')),
  //no need to pass tries in as that defaults to 0 and indicates how
  //  many times the method has tried to get the right result
);

//to use the function:
retryTwiceAndNameIsInResponse(method,url)
.then(response=>console.log('passed, response is:',response))
.catch(error=>console.log('we failed:',error))