I have the next method
async findOne(id: string) {
const coffee = await this.coffeeModel.findById(id);
if (!coffee) throw new NotFoundException('coffee not found');
return coffee;
}
But I want to check if in an array of coffees all exist so I am doing the following:
const coffeesPromises = []
arrayOfCoffees.forEach((element) => {
coffeesPromises.push(this.findOne(element))
})
await Promise.all(coffeesPromises)
//In case 1 coffee does not exist the API return
{
"statusCode": 404,
"message": "coffee not found",
"error": "Not Found"
}
But when I try to wait for the coffee and make a condition with each coffee the error is thrown on the console (in case 1 coffee does not exist) and not as a JSON.
One way I tried to solved it was:
Promise.all(promises).then((results) =>
results.forEach((result) => if (!result.sugar) throw new BadRequestException('coffee has no sugar'))
);
The way Im doing it is the next, but is slow, so that's why Im trying to improve it.
for (const coffee of arrayOfCoffees) {
const coffeeDocuments = await this.findOne(coffee);
if (!coffeeDocuments.sugar)
throw new BadRequestException(
`coffee has no sugar`,
);
}
Which is the best way to handle this?