【发布时间】: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