Saturday, 18 March 2017

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.



via Vishal

No comments:

Post a Comment