userOrganizationGroups

userOrganizationGroups

我知道关于同一错误的讨论有很多问题,而我看到的大多数问题都没有解决我的问题。
我写了这段代码:

const userOrganizationGroups = (organizationGroupsList) => {
 if (Array.isArray(organizationGroupsList) && organizationGroupsList.length) {
    const result = organizationGroupsList.map(async (element) => {
      const { organizationId, groupId } = element;
      const { Organizations, Groups } = models;


      const organization = await Organizations.findOne(
        { _id: organizationId },
        { name: 1, _id: 0 },
      );
      const group = await Groups.findOne({ _id: groupId });
      return Object.assign({}, {
        organizationName: organization.name,
        group: group.name,
      });
    });
    return result;
  }

};


当我调试代码时:

console.log('userOrganizationGroups : ',userOrganizationGroups(list))


我得到了这样的结果:

userOrganizationGroups: Promise { <pending> }


我发现了一个类似的问题:Promise { } - Trying to await for .map,并且使用了问题中提到的解决方案:

const userOrganizationGroups = async (organizationGroupsList) => {


 if (Array.isArray(organizationGroupsList) && organizationGroupsList.length) {
    const result = await Promise.all(organizationGroupsList.map(async (element) => {
      const { organizationId, groupId } = element;
      const { Organizations, Groups } = models;


      const organization = await Organizations.findOne(
        { _id: organizationId },
        { name: 1, _id: 0 },
      );
      const group = await Groups.findOne({ _id: groupId });
      return Object.assign({}, {
        organizationName: organization.name,
        group: group.name,
      });
    }));
    return result;
  }


如何解决此问题?

最佳答案

代替

console.log('userOrganizationGroups : ',userOrganizationGroups(list))

采用

userOrganizationGroups(list).then( groups => console.log('userOrganizationGroups : ', groups)

要么

(async () => { const groups = await userOrganizationGroups(list); console.log('userOrganizationGroups : ', groups);})();

10-04 15:40