简体   繁体   中英

returned promise is undefined in nodejs

I have a function in some model file:

  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;

  });

});

Now I am calling this function as follows from another file:

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

    console.log(selectedGroups);
});

But always, I get selectedGroups as undefined.

I think the problem is :

Before allGroups is returned from async method called getAllGroups, the value of selectedGroups is returned. so it is undefined.

But I don't know how to solve this problem.

You do not return anything from that function (whose name I won't spell out). I think you did not intend to call Group.getAllGroups with a callback, instead you want to use it as a promise:

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;

You might need to promisify it if that doesn't work (like it does for Group.find(…).…() ).


Oh, and you will really want to rewrite that forEach / map / indexOf / splice -thingy (which doesn't even work properly when a group is not found) to a proper simple

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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