2016-11-20 5 views
0

전체 라이브러리를 사용하여 API에서 모든 데이터를 가져옵니다.이 라이브러리는 offset 및 limits 매개 변수로 분리되어 있으며 유한 수는 없습니다. 결과.Node.js - while 루프에서 http 요청이 작동하지 않습니다.

데이터를 반복하는 데 while 조건을 사용하고 결과가 반환되지 않는 시점에서 'incomplete'변수를 false로 설정하여 루프를 종료합니다.

'call_and_retry_last allocation failed' 오류가 발생하기 전까지는 (즉, 데이터베이스에 데이터가 추가되지 않고 콘솔에 아무 것도 출력되지 않으므로) 다음과 같은 코드를 실행하면 아무런 문제가 발생하지 않습니다 (while 루프가 진행될 때 발생 함). 너무 길게). 그러나 while 조건을 모두 제거하면 코드가 제대로 작동합니다.

이것이 작동하지 않는 특별한 이유가 있습니까?

var limit = 50, 
    offset = 0, 
    incomplete = true; 

while (incomplete) { 

    // make api call 
    unirest.get("https://www.theapiurl.com") 
     .header("Accept", "application/json") 
     .send({ "limit": limit, "offset": offset }) 
     .end(function (result) { 

      // parse the json response 
      var data = JSON.parse(result.raw_body); 

      // if there is data 
      if(data .length > 0) 
      { 
       // save the api data 
       // + increase the offset value for next set of data 
       offset += limit; 
      } 
      else 
      { 
       // if there is no data left, end loop 
       incomplete = false; 
       console.log("finished!"); 
      } 
     }); 
    } 
+1

로 recurrcive 기능을 사용할 수 있습니다

여기 내 코드입니다. 그러나 시간이 지나면 귀하의 응답이 들어옵니다. 폭포 또는 시리즈 모델에서 Async.io 또는 어떤 것을 사용하십시오. – Anistark

+1

비동기를 사용하고 코드를 함께 동기화하려고합니다. While 루프가 너무 많은 요청을 보내면 스택 크기 오류가 발생합니다. http://caolan.github.io/async/를 사용하거나 promise 어레이를 만든 다음 Promise.all로 실행하십시오. 희망이 도움이됩니다. –

+1

비동기 동작을 완료하기 위해 루프를 일시 중지하려면 루프의 본문 끝 부분에서'fut.wait()','fut.wait()'의 마지막 부분에서'fut.return()'을 살펴보십시오. '.end'의 본문 (_nodejs_에서만 가능) –

답변

0

당신이 그것을 작동해야

function getServerData(offset){ 

//Your api service with callback.if there is a data then call it again with the new offset. 

} 
function getServerData(1); 
관련 문제