这个问题在这里已有答案:
我正在开发一个项目,其中有一个我需要经历的数组并从MongoDB数据库中查询模型。
完成此查询后,我需要使用查询响应增加另一个数组,但在使用await查询后,查询下的所有内容似乎都被“忽略”。
我试图回复一个承诺,甚至使用.then()但没有任何作用。
const schedules = { all: [], unique: [], final: []};
...
schedules.unique.forEach(async (schedule) => {
const final = await ScheduleRef.findById(schedule);
schedules.final.push(final);
});
假设你是正确的findById
返回一个承诺,你应该能够通过用schedules.unique
迭代map
,然后将await
ed 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);
})();