-1

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.

c_v_w
  • 3
  • 1

1 Answers1

0

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;
kelsny
  • 23,009
  • 3
  • 19
  • 48