Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you return an object from a loop only once the data is ready?

Im new to async functions. I’m trying to return the object name_dates, but when I log it to the console it just returns an empty object.

Here is my code:

async findAllScribesWithProfileName() {

...


let name: string;
let dates: Date[];

type NameDates = { display_name: string; created: Date[] };
const name_dates = <NameDates[]>{};


 owners.forEach(async (owner, ownerIdx) => {
    name = (await this.profileService.getById(owner)).display_name;
    dates = scribes
      .filter((scribe) => scribe.owner == owner)
      .map((s) => s.created);

    name_dates[ownerIdx] = {
       display_name: name,
       created: dates,
     };
  });

 return name_dates;
}

I tried to move the return statement within the owners.forEach loop, but that did not produce the results I was expecting.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use Promise.all and map the array instead so you can await for all of them to complete (in parallel) at once:

await Promise.all(
  owners.map(async (owner, ownerIdx) => {
    name = (await this.profileService.getById(owner)).display_name;
    dates = scribes
      .filter((scribe) => scribe.owner == owner)
      .map((s) => s.created);

    name_dates[ownerIdx] = {
      display_name: name,
      created: dates,
    };
  })
);

return name_dates;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading