1

I know there are many questions discuss about the same error and I saw most of them and they didn't fix my problem. I wrote this code:

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;
  }

};

when I debug the code:

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

I got such a result:

userOrganizationGroups: Promise { <pending> }

I found a similair question: Promise { } - Trying to await for .map and I used the solution mentioned in the question:

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;
  }

How can I fix this issue?

2 Answers 2

2

instead of

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

use

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

or

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks to this article futurestud.io/tutorials/… and your comment I resolved my issue.
0

console.log() was called first because you didn't wait using await or then.

So You should write below instead of
console.log('userOrganizationGroups : ',userOrganizationGroups(list))

;(async () => {
    const resultGroups = await userOrganizationGroups(list)
    resultGroups.forEach(group => {
      console.log(`group: ${JSON.stringfy(group, null, '  ')}`)
    })
})()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.