2017-11-09 4 views
0

私は、Ajaxリクエストをキューに入れるための解決策をたくさん見ていますが、私はこの場合の実装方法を理解しようとしています。それはプッシュとシフトキューでなければなりません?:異なるajaxリクエストを適切にキューに入れよう

var urlList = ['urlA', 'urlB', 'urlC', ...]; 

function initSession() { 
    for (var i = 0; i < urlList.length; i++) { 
     getResponse(urlList[i]); // this is what I would like to queue. 
    } 
} 

function getResponse(theURL) { 
    steps.shuffleLetters({ 
     "text": messages[mesInd] 
    }); 
    $.ajax({ 
     method: 'GET', 
     url: theURL, 
     dataType: 'text', 
     success: function(data) { 
      setTimeout(function() { 
       steps.shuffleLetters({ 
        "text": data 
       }); 
      }, 1000); 
      mesInd = mesInd + 1; 
     }, 
     error: function(data) { 
      setTimeout(function() { 
       steps.shuffleLetters({ 
        "text": "Click Again!" 
       }); 
      }, 1000); 
      mesInd = 0; 
     } 
    }); 
} 
+0

'$ .ajax'は約束を返しています。私はそれが行く方法だと思う。 –

+0

@ kevinSpaceyIsKeyser返されたオブジェクトは 'Promise'のように振る舞いますが、1つではありません:_" jQuery 1.5の '$ .ajax()'によって返されるjqXHRオブジェクトはPromiseインタフェースを実装し、すべてのプロパティ、メソッド、 Promiseの動作 "_ – Andreas

+0

@アンドレアスはヒントのために感謝します。それはちょっとニックピッキング:)? –

答えて

0

forループを除去することによって、それを行うと、現在の要求

の成功は以下のコードを確認した後、次のURLを呼び出すことができます。

var urlList = ['urlA','urlB','urlC',...]; 
var length = urlList.length; 
var currentRequest = 0; 
getResponse(urlList[currentRequest]); 


function getResponse(theURL){ 
steps.shuffleLetters({"text": messages[mesInd]}); 
    $.ajax({ 
     method: 'GET', 
     url: theURL, 
     dataType: 'text', 
     success: function (data) { 
      setTimeout(function(){steps.shuffleLetters({"text": data});}, 1000); 
      //Here you will call the next request 
      currentRequest +=1; 
      if(currentRequest < length) 
      { 
       getResponse(urlList[currentRequest]); 
      } 

      mesInd = mesInd+1; 
     }, 
     error: function (data) { 
      setTimeout(function(){steps.shuffleLetters({"text": "Click Again!"});}, 1000); 
      mesInd = 0; 
     } 
    }); 
} 
+0

ありがとうございます@ Amr-Labib。私の悪い!それでも依頼が次々に行われるようになっても、私は待ち行列に入れられた応答を得ることができません。 – Pierre

+0

待ち行列に入れられた応答はどういう意味ですか?上記のコードは、すべての要求が完了する前に呼び出されることを保証します... –

関連する問題