2017-10-27 15 views
0

私はPromise内でXMLHttpRequestを使用します。サーバーがアイドル状態になることがあるため、エラーが発生した場合は3つのアテンプトを実行したいと考えています。XMLHttpRequest - xhrエラーのデータを再送信

ただし、以下のようにObject state must be opened行のエラーxhr.send()function sendData()にしてください。どうして?

私は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(); 
    }); 

答えて

1

代わりsendData()で再び呼び出されるスケジュール_callService(url, postData, attempts)multiple, sequential fetch() Promiseを参照してください。

function callService(attempts) { 
 
    return new Promise(function(resolve, reject) { 
 
    setTimeout(function() { 
 
     if (attempts < 3) 
 
     reject(++attempts) 
 
     else 
 
     resolve("done"); 
 
    }, Math.floor(Math.random() * 1200)) 
 
    }).catch(function(err) { 
 
    throw err 
 
    }) 
 
} 
 

 
function request(n) { 
 
    return callService(n) 
 
    .then(function(data) { 
 
     console.log(data); 
 
     return data 
 
    }) 
 
    .catch(function(err) { 
 
     console.log(err); 
 
     return typeof err === "number" && err < 3 ? request(err) : typeof err !== "number" ? new Error(err) : "requested " + err + " times"; 
 
    }) 
 
} 
 

 
request(0) 
 
    .then(function(done) { 
 
    console.log("done:", done) 
 
    }) 
 
    .catch(function(err) { 
 
    console.log(err) 
 
    })

+0

エラーが発生した場合XHR状態が常に行われているのですか? –

+0

参照_完了\t完了(数値4)\t転送中にデータ転送が完了したか、転送中に問題が発生しました(無限リダイレクトなど)。 "_ https://xhr.spec.whatwg.org/#states、http ://jsfiddle.net/uxae61c8/ – guest271314

+0

fantastic!あなたの助けをたくさんありがとう! –

関連する問題