As I develop a filter feature, I have categories and cities in the format: ['New York'], ['Cars']
. The goal is to iterate through them to retrieve products based on each city or category. My approach involves storing these products in the products
variable and then returning them to the user.
However, I encounter an issue with retrieving the products. When I log the products
in the async function, it shows the products. But even though I push them into the promises
array, the array remains empty when I invoke Promise.all
.
I understand that the promises need to resolve, so my expectation is to gather them in the promises
array and await their resolution with Promise.all
at the end to process the data and return all collected products. Unfortunately, the promises
array stays empty.
import { Product } from "../../models";
import { Response } from "../../utils";
export default async function ProductsFilters(req, res) {
try {
const { Cities, Categories } = req.body;
let products = [];
let promises = [];
if (Cities.length > 0) {
Cities.map(async (city) => {
const results = await Product.find({ City: city });
return promises.push(results);
});
}
if (Categories.length > 0) {
Categories.map(async (category) => {
const results = await Product.find({ Category: category });
return promises.push(results);
});
}
const results = await Promise.all(promises);
results.map((result) => products.push(result));
if (products.length > 0) Response( res, 200, true, "All products successfully retrieved.", products);
else Response(res, 404, false, "No products found on the platform.", null);
} catch (error) {
Response( res, 500, false, "Internal Server Error while fetching products.", null);
}
}
I rely on Mongo Database and Mongoose for product retrieval, as the .find
function serves to fetch matching products.