monkeyUser
monkeyUser

Reputation: 4671

Nestjs exception inside a loop

I have a loop like this:

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

where getUserChannel function is:

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

If the getUserChannel return a HttpException, Nest doesn't return the error in my response. I can try the same function (getUserChannel), outside the foreach, and I can retrieve the response with 404 Status code.

UPDATE

After the answers, my code is:

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)

It could help someone

Upvotes: 0

Views: 701

Answers (1)

Jay McDoniel
Jay McDoniel

Reputation: 70131

Array.prototype looping methods do not handle async methods correctly, and are actually synchronous in nature, so the execution fires and forgets about the promise and eventually resolves to a 200 even if there is an error thrown. To get around this. you can return the promises from a Array.prototype.map and use await Promise.all(promises) to get proper error handling if one of them tends up throwing an error.

Upvotes: 1

Related Questions