-1

I'm working on a project where there is an array that I need to go through and query a model from my MongoDB database.

After this query is done, I need to increment another array with the query response, but after I query using await, everything under the query seems to be 'ignored'.

I've tried to return a promise, or even use .then () but nothing works.

const schedules = { all: [], unique: [], final: []};
...
schedules.unique.forEach(async (schedule) => {
const final = await ScheduleRef.findById(schedule);
  schedules.final.push(final);
});

1 Answers1

0

Assuming that you're correct that findById returns a promise, you should be able to gather all the promises together by iterating over schedules.unique with map, and then assigning the value of the awaited Promise.all to schedule.final.

const schedules = { all: [], unique: [], final: []};

(async () => {
  const finds = schedules.unique.map(schedule => {
    return ScheduleRef.findById(schedule);
  });
  schedules.final = await Promise.all(finds);
})();
Andy
  • 61,948
  • 13
  • 68
  • 95