【问题标题】:NestJS: "NotFoundException" from my service does not work correclty if I use it in a loopNestJS:如果我在循环中使用它,我的服务中的 \"NotFoundException\" 将无法正常工作
【发布时间】:2022-11-24 07:02:07
【问题描述】:

我有一个简单的“findOne 练习”服务,如果练习的 ID 在数据库中不存在,它会抛出“NotFoundException”。

这是此服务的代码:

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

我期望的是,如果身体中的一项锻炼不存在,我的“锻炼服务”会抛出“notfoundexception”。相反,我收到了这个错误:

/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)并且它有效。但是如果我在循环中使用它,它就不起作用。

【问题讨论】:

    标签: nestjs


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-24
      • 2013-05-16
      • 2016-11-19
      • 1970-01-01
      • 2018-10-22
      • 2020-04-24
      • 2015-07-02
      相关资源
      最近更新 更多