Javascript异步函数

时间:2013-08-29 20:37:05

标签: javascript node.js asynchronous

我试图串联调用3个函数,但是最后一个函数也有一个for循环我有下面的代码但是当我运行它时,我得到callback()之后调用的calanderItems.push()错误}}:

if (called) throw new Error("Callback was already called.");


 async.series([

    function(callback){
        //some database query
                    callback();
    },
    function(callback){
                    //other database query
        callback();
    },
    function(callback){
        var google_calendar = new gcal.GoogleCalendar(req.user.accessToken);
        var calenderItems = [];
        google_calendar.calendarList.list(function(err, calendarList) {
            async.each(calendarList.items, function (item, callback){ 
                google_calendar.events.list(item.id, function(err, calenderItem) {
                    calenderItems.push(calenderItem);
                    callback();
                });
            },function(err){
                for (var element in prettyArray){
                    calenderitems.push(prettyArray[element])
                }
                console.log(calenderitems);
            });
        });
    }

]);

1 个答案:

答案 0 :(得分:0)

我认为您应该将代码更改如下:

if (called) throw new Error("Callback was already called.");


 async.series([

    function(callback){
        //some database query
                    callback();
    },
    function(callback){
                    //other database query
        callback();
    },
    function(callback){
        var google_calendar = new gcal.GoogleCalendar(req.user.accessToken);
        var calenderItems = [];
        google_calendar.calendarList.list(function(err, calendarList) {
            async.each(calendarList.items, function (item, callback){ 
                google_calendar.events.list(item.id, function(err, calenderItem) {
                    calenderItems.push(calenderItem);
                    callback();
                });
            },function(err){
                for (var element in prettyArray){
                    calenderItems.push(prettyArray[element]) // Be careful, you were using a variable that was not in the scope (calenderitems)
                }
                console.log(calenderItems);
                callback(); // This is necessary
            });
        });
    }

]);