0

I wrote this functions which correctly log the value that I expected (an array of partecipants id only):

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;
        });
    },

The log shows something like this:

[ { id: 'user1' } , { id: 'user2'} ]

When I try to call this function from my middleware, it doesn't show the same values (instead it gives me undefined):

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

How can I get the value that I expected on my middleware?

This code is running on a Node.js back-end

pittuzzo
  • 493
  • 8
  • 29

1 Answers1

0

The problem is your return statement is returning from an anonymous function to this._getPartecipants, but the result from this._getPartecipants is not being returned to you.

Try:

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;
    });
},
Pedro Henrique
  • 601
  • 6
  • 17
  • I understood that the problem is due to the return statement, but the solution propose doesn't work – pittuzzo Feb 15 '17 at 14:02