2013-09-30 2 views
0

캘린더에서 사용자의 모든 일정을 표시해야합니다. 모든 캘린더 목록을 얻은 다음 각 이벤트를 반복하여 이벤트를 가져 와서 배열에 저장하려고합니다.값을 배열 nodejs로 푸시

app.get('/getEventsList/', function (req, res) { 
newArray = []; 
function Done(){ 
console.log(newArray); 
} 

function getEventsforOneCalendar(token,calid){ 
gcal(token).events.list(calid, function(err, eventsList) { 
      newArray.push(eventsList); 
      }); 
} 
function getEventsList(token) { 

    gcal(token).calendarList.list(function (err, calendarList) { 
     if (err) { 
    //handle error 
     } else { 
      calendars = calendarList.items; 
      forEach(calendars, function (item, index) { 
      getEventsforOneCalendar(token,item.id); 
     }, Done); 

     } 
    }); 
} 
getEventsList('xxxxxxxxxxxtoken'); 

});

문제는 : 해당 줄 newArray.push (eventsList);

이 줄에 정적으로 전달 된 값은 처럼 보이지 않습니다. newArray.push ('test'); 오류가 발생하지 않습니다. 로그를 기록하면 콘솔에 표시되지만 배열에는 추가되지 않습니다.

무엇이 잘못된 것일까 요?

+0

'newArray'범위가 속한 위치와 언제 호출하는지에 따라 다릅니다. 'getEventsforOneCalendar' 호출이 async이기 때문에 당신이 찾고있는 시점에 그것이 출력되지 않을 수도 있습니다. 이벤트리스트를 표시하기 위해 정확히 어디에서 'newArray'를 사용하는지 알 수 있도록 여기에 더 많은 코드를 넣으십시오. – Kamrul

+0

Kamrul- 사용자가 페이지 (getEventsList)를 요청할 때 코드를 추가했습니다. 나는 그것이 범위 문제라고 생각하지만 해결 방법을 확신 할 수 없습니다. 감사! –

+0

newArray가 로컬 인 경우 두 번째 줄 앞에'var'을 추가하십시오. –

답변

1

가장 간단한 방법은 이와 같을 수 있습니다. 모두 당신이 그것을 보여주고 싶은 방법에 달려 있습니다.

app.get('/getEventsList/', function (req, res) { 
var newArray = []; 
var total; 
function display() { 
    console.log(newArray); 
} 

function getEventsforOneCalendar(token,calid){ 
gcal(token).events.list(calid, function(err, eventsList) { 
       newArray.push(eventsList); 
       if (total == newArray.length) 
        display(); 
      }); 
} 
function getEventsList(token) { 

    gcal(token).calendarList.list(function (err, calendarList) { 
     if (err) { 
    //handle error 
     } else { 
      calendars = calendarList.items; 
      total = calendars.length 
      forEach(calendars, function (item, index) { 
       getEventsforOneCalendar(token,item.id); 
      }, Done); 

     } 
    }); 
} 
getEventsList('xxxxxxxxxxxtoken'); 

}); 
+0

Kamrul, 고맙지 만 여전히 newArray.push (eventsList); 수 없습니다. 이 범위에서 newArray에 액세스하십시오. 왜 표시 함수가 호출 될 때 배열이 비어 있습니다. –

+0

'app.get' 콜백의 범위에 대해'newArray' 앞에'var'을 추가했습니다. 'newArray'를 정의 할 것입니다. 다시 확인하십시오. – Kamrul

+0

Kamrul, 당신이 옳았 어! 정말 고맙습니다! –