未定义函数结果

时间:2017-02-15 12:00:31

标签: javascript

我编写了这个函数,它正确记录了我期望的值(仅限于一个partecipants id数组):

getPartecipantsList: function(roomId){
        this._getPartecipants(roomId,function(err,data){
            partecipants_to_send = [];
            for (i=0; i< data.partecipants.length; i++){
                partecipants_to_send.push({ id : data.partecipants[i].id });
            }
            console.log(partecipants_to_send);
            return partecipants_to_send;
        });
    },

日志显示如下:

  

[{id:&#39; user1&#39; },{id:&#39; user2&#39;}]

当我尝试从我的中间件调用此函数时,它没有显示相同的值(而是它给了我undefined):

...
router.route('/:id/partecipants')
    .get(function(req,res){
        partecipants_list = RoomsManager.getPartecipantsList(req.room._id);
        console.log(partecipants_list);
....

如何获得我期望在中间件上获得的值?

此代码在Node.js后端运行

1 个答案:

答案 0 :(得分:0)

问题是你的return语句从匿名函数返回到this._getPartecipants,但是this._getPartecipants的结果没有返回给你。

尝试:

getPartecipantsList: function(roomId){
    return this._getPartecipants(roomId,function(err,data){
        partecipants_to_send = [];
        for (i=0; i< data.partecipants.length; i++){
            partecipants_to_send.push({ id : data.partecipants[i].id });
        }
        console.log(partecipants_to_send);
        return partecipants_to_send;
    });
},