Unable to fulfill all the promises in JavaScript

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.

Answer №1

When using the map method, it's important to note that it is synchronous even when a callback function passed to it is asynchronous:

Cities.map(async (city) => {
    const results = await Product.find({ City: city });
    return promises.push(results);
});

The callbacks will return immediately upon encountering await, leaving the promises array empty when the .map() call finishes.

Furthermore, remember that map actually returns an array, but in this case, you're missing out on utilizing that returned array by calling push within the map callback. It is recommended to use forEach or a traditional loop like for if you don't need the returned array. If you do require populating an array, make sure to leverage the array returned by map.

Here's a revised version of the code snippet:

async function ProductsFilters(req, res) {
    try {
        const { Cities, Categories } = req.body;
        const products = await Promise.all([
            ...Cities.map(async (City) => Product.find({ City })),
            ...Categories.map(async (Category) => Product.find({ Category }))
        ]);
        if (products.length > 0) {
            Response(res, 200, true, "All products retrieved successfully.", products);
        } else {
            Response(res, 404, false, "No products found on platform.", null);
        }
    } catch (error) {
        Response(res, 500, false, "Internal server error occurred while fetching products.", null);
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

To close the Muix DateTimePicker, simply hit the Escape key or click anywhere outside of the picker

I'd like the DateTimePicker to only close when the user presses the action buttons, not when they click outside or press Escape. Unfortunately, I haven't found any props to control this behavior yet. <DesktopDatePicker closeOnSelect={false} s ...

What causes the body onload = javascript function to run repeatedly?

Greetings for the absolute beginners out there, just dipping your toes in AJAX. I'm curious to know what exactly triggers the continuous change in divMessage content when the text "myName" is altered. 1) It appears that the Javascript function proce ...

Leveraging ES6 Symbols in Typescript applications

Attempting to execute the following simple line of code: let INJECTION_KEY = Symbol.for('injection') However, I consistently encounter the error: Cannot find name 'Symbol'. Since I am new to TypeScript, I am unsure if there is somet ...

The radio buttons are stuck and not changing their selection

Having a group of radio buttons with the same name, when one is checked, it automatically selects another one in the group. Here is my current code: <input name="a" type="radio"> <input name="a "type="radio" checked> JS $("input[type='r ...

Error: The provided `anchorEl` property for this component is invalid

While working on my React 18.2 app with MUI 5.10.5, I encountered an issue trying to create a <Menu /> element that should open when a button is clicked. The menu does appear, but the positioning seems off as it displays in the top-left corner of the ...

What strategies can I implement to ensure my modal dialog box remains responsive? Adjusting the window size causes the modal box to malfunction and lose its structure

Whenever I adjust the size of the browser window, the elements inside the modal box become misaligned. HTML <div class='modal'> <div class='modal-content'> </div> </div> Below is the CSS for the modal ...

Create names for links using jQuery based on the data received from an AJAX response

I am currently utilizing the jQuery UI tooltip script available at this link. As a result, I have tooltip links with varying "data-id" attributes like so: <a tooltip-link data-id="12555"></a> <a tooltip-link data-id="38"& ...

Steps for identifying if the line before in a textarea is blank

Is there a way to identify the structure of individual lines within a textarea? As an example, consider the following contents in my textarea: this is the first line in textarea 1234 this is the second line starting with 1234 this is the fourth line and ...

Requesting for a template literal in TypeScript:

Having some trouble with my typescript code, it is giving me an error message regarding string concatenation, const content = senderDisplay + ', '+ moment(timestamp).format('YY/MM/DD')+' at ' + moment(timestamp).format(&apo ...

Implementing Dynamic Styling Using Parent Component in React Native

I am facing an issue with a <Text> component that is receiving a style through props... TextFile.js: <Text style={styles.text}> This is a line of text and this might be a second line </Text> screenFile.js: <View style={styles.v ...

Why is webpack attempting to package up my testing files?

In my project, I have two main directories: "src" and "specs". The webpack configuration entrypoint is set to a file within the src directory. Additionally, the context of the webpack config is also set to the src directory. There is a postinstall hook in ...

Failure to execute the success function

My current issue involves making an AJAX call to retrieve a record from the database. Despite console logs showing that the record is successfully returned, the success function fails to execute. function ajaxForParent() { var search = document.getEle ...

Activate animation while scrolling the page

I am using a progress bar with Bootstrap and HTML. Below is the code snippet: $(".progress-bar").each(function () { var progressBar = $(this); progressBar.animate({ width: progressBar.data('width') + '%' }, 1500); }); <body> & ...

Obtaining a JavaScript proxy from a WCF service using webHttpBinding

I have configured all the necessary endpoints, bindings, and behaviors to consume a service using JSON. However, I am struggling to find a way to generate a JavaScript proxy for accessing the service from my client-side JavaScript with jQuery through Ajax. ...

"Enhabling tablesorter pagination to ensure that buttons always stay in sync with

I am experiencing an issue with the pagination buttons staying at the bottom of my page, even when there are only 2 entries left on the last page. Check out my table here: Is there a way to make the pagination buttons dynamically move to the top based on ...

Ensure that the extension is only loaded once Angular has fully loaded

I am currently working on a Chrome extension that incorporates event listeners to elements within a page utilizing Angular 1.2.10. The following code snippet is an example of what I have: window.addEventListener("load", (event) => { var switchButton = ...

exploring XML documents

With around 250,000 XML files, each named with a UUID, I am looking for the most effective way to perform a full text search on these files and identify the UUID of the matching ones. What would be the optimal approach for indexing them in a nodejs environ ...

How do useCases interact with each other within Clean Architecture principles in NodeJS?

I'm currently working on implementing Bob Martin's Clean Architecture in my project, and I have a question. How do use-cases interact with each other? For instance: In my project, there are entities for Department and Employee. The Department ...

Guide to increasing a field value in Backendless.com

Below is an overview of the table structure I have: Table data ---------------------------------- - User - ---------------------------------- | objectId | name | password | ---------------------------------- | z12ttttt | ...

Ensure $q.all does not produce an error when one promise is not resolved

While geocoding addresses, there are instances where some fail. My goal is to retrieve the successful results and disregard the failed ones in order to display the coordinates on a map. Currently, using $q.all triggers the errorHandler when one promise i ...