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?
CodePudding user response:
Array.forEach technically ignores Promise(async/await). If you want to use Promise.all with array you'd better to use Array.map. The code would be something like this.
async findOne(id: string) {
const coffee = await this.coffeeModel.findById(id);
if (!coffee) throw new NotFoundException(`coffee ${id} not found`);
return coffee;
}
const promises = arrayOfCoffees.map(async element => await this.findOne(element))
await Promise.all(promises).catch(e => /* error handling goes here */)
// or shortly
await Promise.all(arrayOfCoffees.map(async element => await this.findOne(element)))
.catch(e => /* error handling goes here */)
As you can see the last line, I put an error handler to Promise.all. Because if Promise.all meets an error while running all the other promises it emits an error.
CodePudding user response:
change forEach
with for (const item of items)