2014-02-19 3 views
0

폴링 결과가 예상 한 결과로 돌아올 때까지 계속 호출해야하는 아약스 폴링 기능을 구현했습니다. 이 작업을 수행하기 위해 지연을 도입하기 위해 setTimeout을 사용하여 결과를 얻을 때까지 함수가 서버를 요청으로 망치는 일이 없도록합니다.setTimeout에서 예기치 않은 동작

내가 예상 한 동작을 얻으려면 코드를 구현해야하는 방식을 이미 찾았습니다. 하지만, 내 질문은 내가 찾은 해결책에 관한 것이다. 나는 왜 솔루션이 타임 아웃과 올바르게 작동하는지 알기를 원한다. 요청과 서버 여기

function makeRequest(url, data, requestType, successCallback, errorCallback, doneCallback) { 
    $.ajax({ 
     url: url, 
     type: requestType, 
     data: data != null ? JSON.stringify(data) : '', 
     contentType: 'application/json; charset=utf-8', 
     success: function (success) { 
      if (successCallback) successCallback(success); 
     }, 
     error: function (error) { 
      if (errorCallback) errorCallback(error); 
     }, 
     done: function() { 
      if (doneCallback) doneCallback(); 
     } 
    }); 
} 

function pollForResult(Id) { 
    setTimeout(function() { 
     makeRequest('/Transaction/TransactionResult/' + Id, 
      null, 
      "GET", 
      function(result) { 
       //success code here 
      }, function(error) { 
       //error callback implementation here 
       if (error.status === 404) { 
        pollForResult(Id); //results not ready, poll again. 
       } else { 
        alert("stopped polling due to error"); 
       } 
      }, null); 
    }, 2000); 
} 

제대로 단지 지속적으로 시간 제한을 설정하지 않는 코드 안타 : 여기

성공적으로 결과에 대한 시간 제한 및 여론 조사를 설정하는 작업 코드

function pollForResult(Id) { 
    makeRequest('/Transaction/TransactionResult/' + Id, 
     null, 
     "GET", 
     function(result) { 
      //success code here 
     }, function(error) { 
      //error callback implementation here 
      if (error.status === 404) { 
       setTimeout(pollForResult(Id), 2000); //results not ready, poll again. 
      } else { 
       alert("stopped polling due to error"); 
      } 
     }, null); 
} 

그럼, 내 질문은 다음과 같습니다. 두 번째 코드 블록이 폴링을 2 초간 기다리는 대신 결과를 얻기 위해 서버를 계속 폴링하는 이유는 무엇입니까? 나는 시도하지 않은 있지만

나는이 코드의 두 번째 블록에서 제대로 작동 것이라고 의심 즉시

setTimeout(function(){ pollForResult(Id); }, 2000); //results not ready, poll again. 

답변

3
setTimeout(pollForResult(transactionId),2000); 

이 코드 전화 pollForResult반환 값을 할당 시간 초과가 발생할 때 호출되는 함수입니다.

클로저를 작성하고이를 시간 초과로 전달하는 함수가있을 수 있기 때문에 이는 바람직한 동작입니다. 그러나 그것은 많은 사람들을 잡으려고하는 것 같습니다 ...

당신이 말했듯이, function() {pollForResult(transactionId);} 잘 작동합니다.

+0

+1, [Function.prototype.bind()] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind)도 사용할 수 있습니다.'' 짧은 구문을 선호한다면 setTimeout (pollForResult.bind (null, transactionId), 2000); (참고 : [polyfill] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Compatibility)을 사용하지 않으면 IE 9 이상이 필요합니다.) – ComFreek

+1

@ComFreek '.bind()'*가 함수 (클로저)를 반환하기 때문에 작동하는 이유는^_ ^ –