2017-03-18 65 views
0

我有一些模型文件中的函數:返回承諾在的NodeJS未定義

Group.getGroupsOtherThanSelectedGroupAndItsDescendents(groupId, 100).then(function(selectedGroups) { 

    console.log(selectedGroups); 
}); 

但始終,我得到selectedGroups:

module.exports.getGroupsOtherThanSelectedGroupAndItsDescendents = wrap(function*(topGroupId, generations) { 

    const topGroup = yield Group.find({parent: topGroupId}).populate('parent').populate('effect').populate('nature'); 

    let groups = []; 
    let ids = [topGroupId]; 

    for(let i = 0; i < generations; i++) { 
    const thisLevelGroups = yield Group.find({ parent : { $in : ids } }).populate('parent').populate('effect').populate('nature'); 
    ids = thisLevelGroups.map(group => group._id); 
    groups = groups.concat(thisLevelGroups); 
    } 

    Group.getAllGroups(function(err, allGroups) { 

    groups.forEach(function(group) { 
     var index = allGroups.map(function(thisGroup) { return thisGroup.name; }).indexOf(group.name); 
     allGroups.splice(index, 1); 
    }, this); 

    return allGroups; 

    }); 

}); 

現在從另一個文件如下,我調用這個函數未定義。

我認爲這個問題是:

allGroups之前從異步方法稱爲getAllGroups返回,返回selectedGroups的價值。所以它是不確定的。

但我不知道如何解決這個問題。

+0

你是否在函數getGroupsOtherThanSelectedGroupAndItsDescendents中返回了一些東西? – caisah

+1

男人,這是一個長功能名稱。 – gyre

+0

@gyre你能建議我小一點嗎? – Vishal

回答

1

你不需要return任何來自該功能的任何東西(我的名字我不會說明)。我想你也沒打算叫Group.getAllGroups有一個回調,而不是你想使用它作爲一個承諾:

var allGroups = yield Group.getAllGroups(); 
//    ^^^^^ 
groups.forEach(function(group) { 
    var index = allGroups.map(function(thisGroup) { return thisGroup.name; }).indexOf(group.name); 
    allGroups.splice(index, 1); 
}, this); 
return allGroups; 

您可能需要promisify,如果不工作(就像它爲Group.find(…).…())。


哦,你真的要重寫forEach/map/indexOf/splice -thingy(它在未發現一羣甚至沒有正常工作)到一個適當的簡單

return allGroups.filter(thisGroup => !groups.some(group => thisGroup.name === group.name)); 
+0

謝謝你的男人。這工作正常。以及'forEach/map/indexOf/splice'的良好捕獲。這部分你的答案對我來說不是必要的。但它會在別的地方有用。因爲組是所有組的子集,所以組永遠不會爲空。 – Vishal

+1

爲了提高可讀性,使用'filter'和'some'是必要的:-) – Bergi

+0

是的你是對的。 – Vishal