bobby123112
bobby123112

Reputation: 13

How to use promises with async/await and for loop in js

I have the following code:

  find_drives: async (req, res) => {
    try {
      const user_location = req.query.user_location;
      const user_destination = req.query.user_destination;

      const drives = await Drive.find({ status: "open" }).lean();
      drives.forEach((drive) => {
        getTravelStats(user_location, drive.departure_location).then(
          (stats) => (drive.start_stats = stats)
        );
        getTravelStats(user_destination, drive.arrival_location).then(
          (stats) => (drive.end_stats = stats)
        );
      });
      res.status(200).json(drives);
    } catch (e) {
      res.status(500).json({ error: e.message });
    }
  },

The start_stats and end_stats properties don't get set, but when I log the stats it works. I think the problem is with how I'm using promises, how would I fix this.

Upvotes: 0

Views: 42

Answers (1)

Amir MB
Amir MB

Reputation: 3430

Since the Array#forEach does not support async functions, you can use for of:

for (const drive of drives) {
    drive.start_stats = await getTravelStats(user_location, drive.departure_location);
    drive.end_stats = await getTravelStats(user_destination, drive.arrival_location);
}

If you want to call getTravelStats in parallel for all drivers:

await Promise.all(drives.map(async (drive) => {
    drive.start_stats = await getTravelStats(user_location, drive.departure_location);
    drive.end_stats = await getTravelStats(user_destination, drive.arrival_location);
}));

Upvotes: 2

Related Questions