Javascript xhr错误时重新发送数据

Javascript xhr错误时重新发送数据,javascript,xmlhttprequest,Javascript,Xmlhttprequest,我在承诺中使用XMLHttpRequest。因为服务器有时是空闲的,所以当出现错误时,我想做3次尝试 但是,执行下面的操作时,必须在函数sendData的xhr.send行上打开对象状态错误。为什么? 我想xhr已经开放了。实现这一目标的正确方法是什么 function _callService(url, postData) { return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequ

我在承诺中使用XMLHttpRequest。因为服务器有时是空闲的,所以当出现错误时,我想做3次尝试

但是,执行下面的操作时,必须在函数sendData的xhr.send行上打开对象状态错误。为什么?

我想xhr已经开放了。实现这一目标的正确方法是什么

function _callService(url, postData) {
    return new Promise(function(resolve, reject) {
        var xhr = new XMLHttpRequest();
        var attempts = 0;
        xhr.open("POST", url);
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                    resolve(xhr.response);
                }
            }
        };
        xhr.addEventListener("error", onXhrError);

        function sendData() {
           //here I get the Object state must be opened when this is called from onXhrError listener
           xhr.send(postData); 
        };

        function onXhrError() {
            console.log("onXhrError");
            if (attempts < 3) {
                attempts += 1;
                sendData();
            } else {
                reject("OnXhrError")
            }
        };

        sendData();
    });
Schedule\u callServiceurl,postData,尝试再次调用而不是sendData,请参阅

函数callServiceattempts{ 返回新的允诺函数解析、拒绝{ setTimeoutfunction{ 如果尝试次数<3 拒绝++尝试 其他的 完成; },Math.floorMath.random*1200 }凯瑟先生{ 失误 } } 函数请求n{ 返回呼叫服务 .Then函数数据{ 控制台日志数据; 返回数据 } 凯瑟先生{ console.logerr; 返回typeof err==number&&err<3?请求错误:typeof err!==number?新错误错误:请求+错误+次数; } } 请求0 1.完成{ console.logdone:,完成 } 凯瑟先生{ console.logerr
}出现错误时是否始终执行xhr状态?请参阅“完成”数值4数据传输已完成或传输过程中出现错误,例如无限重定向,