2017-11-09 5 views
0

아약스 대기열 요청에 대한 해결책이 많이 있지만이 경우에 구현하는 방법을 이해하려고합니다. 그것은 푸시 시프트 큐?다른 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와 같은 역할을하지만 하나가 아닙니다. _ "jQuery 1.5에서'$ .ajax() '에 의해 반환 된 jqXHR 객체는 Promise 인터페이스를 구현하여 모든 속성, 메소드 및 메서드를 제공합니다. 약속의 행동 "_ – Andreas

+0

@ 앙드레아스는 힌트를 주셔서 감사합니다. 그것은 조금 nitpicking :)? –

답변

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

대기중인 응답은 무엇을 의미합니까? 위의 코드는 모든 요청이 완료되기 전에 호출된다는 것을 보장합니다 ... –