繁体   English   中英

返回的promise在nodejs中未定义

[英]returned promise is undefined in nodejs

我在某些模型文件中有一个功能:

  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;

  });

});

现在,我从另一个文件中按以下方式调用此函数:

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

    console.log(selectedGroups);
});

但总是,我将selectedGroups定义为未定义。

我认为问题是:

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

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

您不会从该函数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;

如果这不起作用,则可能需要对它进行Group.find(…).…()就像Group.find(…).…() )。


哦,您真的很想将forEach / map / indexOf / splice -thingy(在找不到组时无法正常工作)重写为适当的简单形式

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM