2014-02-17 19 views
0

我試圖創建數據庫對象陣列控制流程:的Node.js:用foreach

我已經實體「組」至極的hasMany「設備」,我想創建數組白衣所有組以及每個組的他的設備列表:

[ 
{ 
    "group_id": 「1」, 
    "name": 「My_group」, 
    "devices_list": [1, 2, 18] 
}, 
{ 
    "group_id": 「2」, 
    "name": 「My_second_group」, 
    "devices_list": [3, 24] 
} 
] 

我試過幾種方法是這樣的:

Group.all(function (err, groups) { 
    var resJson = {}; 
    groups.forEach(function(group, index){ 
     group.devices(function(err, devices){ 
      resJson[index] = group; 
      console.log(devices); 
      resJson[index].devices_list = devices; 

      //End of the loop 
      if (index == groups.length -1){ 
       send({code: 200, data: resJson}); 
      } 
     }); 
    }); 
}); 

編輯1:

我想這樣太:

var resJson = {}; 
groups.forEach(function(group, index){ 
    group.devices(function(err, devices){ 
     resJson[index] = group; 
     resJson[index].devices_list = []; 

     devices.forEach(function(device,index2){ 
      resJson[index].devices_list.push(device); 
     }); 


     //End of the loop 
     if (index == groups.length -1){ 
      send({code: 200, data: resJson}); 
     } 
    }); 
}); 

但最後,我resJson只包含空組(不包括相關設備組),另一組是不可見的。因此,我的devices_list全部爲空,而console.log(設備)顯示設備。

似乎在處理非空組之前處理「發送」指令。

這樣做的方法是什麼?

謝謝您的時間

+1

這個*不應該是發生了什麼,但我很好奇,如果它是'resJson [index] .devices_list = devices;'line - 你是否嘗試過遍歷設備並將它們添加到設備列表中以看看這是否會改變你的回報?另外,你的'resJson'是一個對象,而不是像你的目標JSON那樣的數組。 –

+0

感謝您的關注,我試過這個,我編輯了我的帖子。 – igor

回答

0

而是跟蹤並使用對列表的長度指數也許你可以使用一個after類型的構造。我真的很喜歡他們,他們很容易整合和服務完成一定次數的完美目的。

首先,讓我們定義一個可以使用的函數。

var after = function(amount, fn) { 
    var count = 0; 
    return function() { 
    count += 1; 
    if (count >= amount) { 
     fn.apply(arguments); 
    } 
    }; 
}; 

現在應該適合您,讓我們修改您的代碼示例以使用它。

var json = []; // To return, you originally wanted an array. 
Group.all(function(err, groups) { 
    if (err) { 
    // Handle the error 
    } else { 
    var sendJson = after(groups.length, function(json) { 
     send({code: 200, data: json}); 
    }); 
    groups.forEach(function(group) { 
     group.devices(function(err, devices) { 
     if (err) { 
      // Handle the error... 
     } else { 
      group.devices_list = devices; 
      json.push(group); // This part is different, using this method you'll match the JSON you gave as your "goal" 
     } 
     // This is outside the if/else because it needs to be called for every group 
     // regardless of change. If you do not call this the exact number of times 
     // that you specified it will never fire. 
     sendJson(json); 
    }); 
    } 
}); 

也許類似的東西可能會清除您的問題。

+0

謝謝你的幫助izuriel,它的工作!實際上,這個指標並不可靠。功能很好後。 – igor