将值推送到数组 nodejs

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19085134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:48:49  来源:igfitidea点击:

pushing values to array nodejs

arraysnode.jsgoogle-apigoogle-calendar-api

提问by Ben Scarberry

I need to display all events of user from his calendars. I get a list of all calendars and then loop through each one get events and try to store them in an array.

我需要从他的日历中显示用户的所有事件。我得到所有日历的列表,然后遍历每个获取事件并尝试将它们存储在一个数组中。

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');

});

});

Problem is: that line newArray.push(eventsList);

问题是:那行 newArray.push(eventsList);

Any value even static passed in this line doesn't go like newArray.push('test'); and no error is thrown. if I log it I see it in the console, but it's never added to the array.

在这一行中传递的任何值甚至是静态的都不会像 newArray.push('test'); 并且不会抛出任何错误。如果我记录它,我会在控制台中看到它,但它从未添加到数组中。

What's possibly wrong?

可能有什么问题?

采纳答案by Kamrul

I simplest way can be like this. All it depends on how you want to show it.

我最简单的方法可以是这样。这一切都取决于你想如何展示它。

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');

});