如何在js中使用async/await和for循环的承诺



我有以下代码:

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

start_statsend_stats属性没有设置,但是当我记录stats时,它可以工作。我认为问题出在我使用承诺的方式上,我该如何解决这个问题?

由于Array#forEach不支持async功能,您可以使用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);
}

如果你想为所有驱动并行调用getTravelStats:

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

最新更新