Javascript 返回的承诺在nodejs中未定义

Javascript 返回的承诺在nodejs中未定义,javascript,node.js,Javascript,Node.js,我在一些模型文件中有一个函数: module.exports.getGroupsOtherThanSelectedGroupAndItsDescendents = wrap(function*(topGroupId, generations) { const topGroup = yield Group.find({parent: topGroupId}).populate('parent').populate('effect').populate('nature'); let

我在一些模型文件中有一个函数:

  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;

  });

});
但我总是把selectedGroups当作未定义的

我认为问题在于:

在从名为getAllGroups的异步方法返回allGroups之前,将返回selectedGroups的值。所以它是未定义的

但是我不知道如何解决这个问题。

您不会从该函数返回任何我不会拼写其名称的内容。我认为您不打算使用回调调用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;
如果这对团队来说不起作用,你可能需要做出承诺。找到

哦,你真的想重写forEach/map/indexOf/splice的东西,当一个组没有找到一个合适的简单组时,它甚至不能正常工作

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

你在函数getgroupsotherthanselectedgroupanditsgendants中返回了什么吗?伙计,这是一个很长的函数名。@gyre你能给我推荐一个较小的吗?怎么样getNonSelectedGroups@gyre是的,这是一个可以接受的名字。谢谢你。那很好。以及forEach/map/indexOf/splice的良好捕获。这部分答案对我来说不是必要的。但在其他地方它会很有用。因为组是所有组的子集,所以组永远不会为空。
return allGroups.filter(thisGroup => !groups.some(group => thisGroup.name === group.name));