【问题标题】:Nestjs exception inside a loop循环内的Nestjs异常
【发布时间】:2022-11-02 00:22:18
【问题描述】:

我有一个这样的循环:

async sendMessage(data:MessageDto,userId:string){
     
        data.targets.forEach (async (channel) => {

            
            let gateway = await this.getUserChannel(userId,channel.channelId);
            
            
            switch (channel.target) {
                case 'Telegram':                            
                    this.telegramService.sendMessageGateway(gateway,data)
                    break;            
                default:
                    break;
            }
        });
    }

其中 getUserChannel 函数是:

    async getUserChannel(userId: string, channelId: string): Promise<IGateway> {
        const currentChannel = await this.GatewayModel.findOne({ userId: userId, channelId: channelId })
        if (!currentChannel) {
            throw new HttpException(`Gateway Not Found`, HttpStatus.NOT_FOUND);        
        }
        return currentChannel;
    }

如果 getUserChannel 返回 HttpException,Nest 不会在我的响应中返回错误。 我可以在 foreach 之外尝试相同的功能 (getUserChannel),然后我可以使用 404 状态码检索响应。

更新

回答后,我的代码是:

let datas = data.targets.map(async (channel) => {
            let gateway = await this.getUserChannel(userId, channel.channelId);
            switch (channel.target) {
                case 'Telegram':
                    await this.telegramService.sendMessageGateway(gateway, data)
                    break;
                default:
                    break;
            }
        })

        let allPromise = Promise.allSettled(datas)

        const statuses = await allPromise;
        console.log(statuses)

它可以帮助某人

【问题讨论】:

    标签: node.js typescript nestjs


    【解决方案1】:

    Array.prototype 循环方法不能正确处理异步方法,实际上是同步的,因此执行会触发并忘记承诺,即使抛出错误,最终也会解析为 200。为了解决这个问题。您可以从Array.prototype.map 返回承诺,并在其中一个倾向于抛出错误时使用await Promise.all(promises) 进行正确的错误处理。

    【讨论】:

    • 对于某些用例,await Promise.allSettled(promises) 优于 await Promise.all(promises)all 将在第一个拒绝的承诺上出错,而​​allSettled 允许您迭代每个承诺的结果并处理多个拒绝。例如,这使您可以记录每个故障,而不仅仅是第一个故障。
    • 谢谢大家,在您的惊人回答之后,我编辑了我的问题。非常感谢
    猜你喜欢
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多