簡體   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