2017-02-15 120 views
0

我寫這功能,這正確登錄,我所期望的值(僅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:「USER1」},{ID:「用戶2」}]

當我嘗試從我的中間件調用此函數,它不會顯示相同的值(而不是它給了我undefined):

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

如何獲得我期望在我的中間件上的價值?

此代碼對Node.js的後端運行

+0

檢查req.room._id是你認爲它是 – Mihai

+0

什麼'req.room._id'的輸出? – callback

+0

[如何從異步調用返回響應?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Andreas

回答

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

我明白這個問題是由於return語句,但解決方案建議不起作用 – pittuzzo