NestJS:如果我在循环中使用它,我的服务中的"NotFoundException"不起作用



我有一个简单的" findOne练习";抛出NotFoundException"如果该练习的ID在数据库中不存在

下面是这个服务的代码:

async findOne(id: string | Exercice) {
if (!isValidObjectId(id)) {
throw new BadRequestException('ID is not valid');
}
const exercice = await this.exerciceModel
.findById(id)
.populate('bodyPart targetMuscle')
.select('-__v');
if (!exercice) {
throw new NotFoundException('exercice not found');
}
return exercice;
}

当我创建一个程序时,我需要确保我发送到程序体中的练习存在于数据库中。所以在我的"创建程序服务"中我这样打电话给我的健身服务。


async create(createProgramDto: CreateProgramDto) {
const { user, exercices } = createProgramDto;

// some code
exercices.forEach(async (element) => {
await this.exerciceService.findOne(element.exercice)
});
const createProgram = new this.programModel(createProgramDto);
return createProgram.save();
}

我所期望的,是我的"锻炼服务"。抛出一个"notfound"异常;如果其中一种锻炼在身体中不存在。相反,我得到了这个错误:

/home/jeremy/src/apps/API/my-exercices/src/modules/exercice/exercice.service.ts:62
throw new NotFoundException('exercice not found');
^
NotFoundException: exercice not found
at ExerciceService.findOne (/home/jeremy/src/apps/API/my-exercices/src/modules/exercice/exercice.service.ts:62:13)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
at /home/jeremy/src/apps/API/my-exercices/src/modules/program/program.service.ts:29:6

下面是我如何发送数据来创建一个程序:

{
"title": "Test",
"user": "634c1bd3c3d17e1b50c2b946",
"exercices": [
{
"exercice": "637d116882ce1f7cc732d83c",
"totalSet": "1",
"rest": "1"
},
{
"exercice": "637d116882ce1f7cc2d83c",
"totalSet": "1",
"rest": "1"
}
]
}

我确实尝试使用没有循环的服务(通过在代码库中添加ID),它的工作。但是如果我在循环中使用它,它就不起作用了。

Array.prototype方法不能正确处理异步代码,所以当你可以在其中使用async/awaittry/catch时,这些承诺的执行将在后台和请求范围之外(因此是Nest的异常过滤器)意味着你有悬空的承诺。如果您绝对需要迭代数组并执行异步方法,那么最好的选择是使用await Promise.allSettled(array.map(async(arrayObject) => someAsyncFunction)),以便您实际等待所有承诺被拒绝或解析

最新更新