如何修复NestJS中未处理的承诺拒绝警告

时间:2020-10-13 18:36:10

标签: angular typescript warnings backend nestjs

我正在将NestJS用于我的后端有角项目,并且已放置方法。在安装swagger之前,它运行良好,但是在安装swagger之后,我收到警告,说未处理的承诺被拒绝,并且它不允许我运行。

它工作正常,如果我在控制器中注释了代码,那么我认为async / await存在问题,但不确定如何解决它,因此,如果能获得有关如何解决的任何帮助或建议,我将不胜感激这个吗?

控制器

    @Put(':id')
    async updateHelpSubsection(@Body() newHelp: HelpSubsectionModule, @Param() params): Promise<HelpSubsectionModule> {
        try{
            let oldHelpData = await this.helpSubsectionService.getHelpSubsectionbyId(params.id)
            return this.helpSubsectionService.updateHelpSubsection(oldHelpData, newHelp);
        }catch(e) {
            console.log(e)
        }
    }

服务

    async updateHelpSection(updateHelp: HelpSectionEntity, newHelpData): Promise<HelpSectionEntity> {

        Object.keys(newHelpData).forEach((key) => {
            updateHelp[key] = newHelpData[key];
        });

        try {
            return await this.helpSectionRepo.save(updateHelp);
        } catch (err) {
            throw new HttpException({
                error: err
            }, HttpStatus.FORBIDDEN)
        }
    }

这是我收到的警告。 enter image description here

3 个答案:

答案 0 :(得分:1)

请在控制器中对此进行更新:

       @Put(':id')
       async updateHelpSubsection(@Body() newHelp: HelpSectionEntity, @Param() params): Promise< HelpSectionEntity> {
           try{
               let oldHelpData = await this.helpSubsectionService.getHelpSubsectionbyId(params.id)
               return this.helpSubsectionService.updateHelpSubsection(oldHelpData, newHelp);
           }catch(e) {
               console.log(e)
           }
       }

打字稿中的类型中不允许使用模块。

请用 HelpSectionEntity 替换 HelpSubsectionModule

答案 1 :(得分:0)

不太确定@Put(:id)的工作方式,但是updateHelpSection返回了一个承诺,因此,如果承诺被解决,则必须使用.then()处理它以返回数据,并抛出catch()如果诺言被拒绝,则会出错。检出此article

答案 2 :(得分:0)

您看到的只是对良好做法的警告。

每个Promise必须具有一种方法来捕获发出请求时将产生的错误

例如:

这是诺言。

const slowAndSteady = new Promise(function(resolve, reject) {
    reject();
});

如果您这样使用async / await。

(async function() {
    await slowAndSteady();
})();

您将获得UnhandledPromiseRejectionWarning,但如果您以此方式使用。

slowAndSteady
    .then(function(result) {
        console.log('result', result);
    })
    .catch(function(err) {
        console.log('error: ', err);
    });

警告消失。

但是如果您仍然需要使用async / await,则有两种选择。

(async () => {
  try {
    const result = await slowAndSteady();
    console.log('result', result);
  } catch(e) {
    console.log('Error caught',e);
  }
})();

(async () => {
  const result = await slowAndSteady().catch((e) => console.log('Error caught',e));
  console.log('result', result);
})();