2016-12-06 13 views
0

複数の要求を非同期で送信しようとしていますが、残りの1つだけが終了しています - 残りはすべてxmlhttp.status == 0xmlhttp.readyState == 1です。ES6での非同期要求処理

どういうところが間違っていますか?

私はApi.jsAjax.jsの2つのファイルを持っています。 APIは、アヤックスを使用して要求を送信している:

Api.js

import Ajax from './Ajax'; 

class Api { 

    returnData (success, failure) { 
     var params = { 
      methodId: this.ids.returnData, 
      requestBody: {} 
     }; 
     this.sendRequest(params, success, failure); 
    }; 

    sendRequest (data, success, failure) { 
     Ajax.execute(function (response) { 
      success(response); // simplified 
     }); 
    }; 

} 

export default new Api(); 

Ajax.js

class Ajax { 

    createXmlHttp() { 
     if (window.XMLHttpRequest) { 
      this.xmlhttp = new XMLHttpRequest(); 
     } else { 
      this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
     } 
    }; 

    onreadystatechange (action, data) { 
     this.xmlhttp.onreadystatechange = function() { 
      if (this.xmlhttp.readyState === 4) { 
       if (this.xmlhttp.status === 200) { 
        action(this.xmlhttp.responseText); 
       } 
      } 
     }.bind(this); 
    }; 

    execute (action, url, data) { 
     this.createXmlHttp(); 
     this.onreadystatechange(action, data); 
     this.xmlhttp.open("POST", url, true); 
     this.xmlhttp.setRequestHeader("Content-Type", "text/plain"); 
     this.xmlhttp.send(data); 
    }; 

}; 

export default new Ajax(); 
+0

「0」は不完全なリクエストだけではなく、エラーコードでもあります...あなたが書いたコードにはエラー処理がありません。 –

答えて

4

あなたしかあなたのAjaxオブジェクトのインスタンスを1つ作成します。

あなたがAjax.executeを呼び出すたびに、あなたはあなたが要求ごとにAjaxの新しいインスタンスを必要とするthis.xmlhttp = new XMLHttpRequest();

を上書きします。あなたは、新しいオブジェクトが必要なときにそれを作る...

export default Ajax; 

export default new Ajax(); 

がインスタンスを作成しないでください。

sendRequest (data, success, failure) { 
    new Ajax.execute(function (response) {