如何在for-each循环中使用async-await? [重复]

问题描述 投票:-1回答:1

这个问题在这里已有答案:

我正在开发一个项目,其中有一个我需要经历的数组并从MongoDB数据库中查询模型。

完成此查询后,我需要使用查询响应增加另一个数组,但在使用await查询后,查询下的所有内容似乎都被“忽略”。

我试图回复一个承诺,甚至使用.then()但没有任何作用。

const schedules = { all: [], unique: [], final: []};
...
schedules.unique.forEach(async (schedule) => {
const final = await ScheduleRef.findById(schedule);
  schedules.final.push(final);
});
javascript node.js async-await
1个回答
0
投票

假设你是正确的findById返回一个承诺,你应该能够通过用schedules.unique迭代map,然后将awaited Promise.all的值分配给schedule.final来收集所有的承诺。

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

(async () => {
  const finds = schedules.unique.map(schedule => {
    return ScheduleRef.findById(schedule);
  });
  schedules.final = await Promise.all(finds);
})();
© www.soinside.com 2019 - 2024. All rights reserved.