Hold off on transmitting information until all Promises have been fulfilled

I'm facing an issue where I need to query my database twice, log the data, and then send it. However, due to the promise not resolving in time, I am unable to send the data promptly. Can someone advise me on how to ensure that all promises are resolved before sending the data? Any help would be greatly appreciated.

app.get("/organizations/:slug_id/:category_id", function(req, res, next) {
    queries.getAllProducts(req.params.category_id)
      .then(function(result) {
            return result.map(function(obj) {
                queries.getAllProductsImages(obj.product_id)
                  .then(function(images) {
                        obj["images"] = images;
                        return obj;
                  })
                })
              })
            .then(function(products) {
              res.status(200).json(products)
            })
              .catch(function(error) {
                next(error);
              });
});

Answer №1

Give this code a try:

app.get("/organizations/:slug_id/:category_id", function (req, res, next) {
    queries.getAllProducts(req.params.category_id)
        .then(function (result) {
            return Promise.all(result.map(function (obj) {
                return queries.getAllProductsImages(obj.product_id)
                    .then(function (images) {
                        obj["images"] = images;
                        return obj;
                    });
            }));
        })
        .then(function (products) {
            res.status(200).json(products)
        })
        .catch(function (error) {
            next(error);
        });
});

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

Scale transformation - I am aiming for it to exceed the limits, yet it remains contained within

Currently, I am working on enhancing my carousel by implementing a zoom effect when hovering over the images. However, I have encountered an issue where the image gets hidden within the div container and doesn't overflow as expected. I tried adjusting ...

How can you use jQuery to add a select element dynamically and then clear the selected choice?

Trying to build a dynamic form in the Play Framework, but my javascript skills are lacking. I found this jQuery example for adding fields dynamically, but I want to add both a text field and a select box each time. My attempt involves using this answer ...

Tips on how to dynamically allocate an id value to a jQuery function that retrieves the backgroundImage URL

I have a div with a background image and I am using a jQuery function to retrieve the URL of the background image. var name=image; var url=$("#"+name+"").css("background-image"); console.log(url); <script src="https://cdnjs.cloudflare.com/aj ...

The `react-hover` npm package functions flawlessly in the development environment despite being excluded from the production build

While working on my project, I decided to utilize the npm package react-hover and it's been effective during local development in dev build. However, when I execute the npm run build command to serve the production version, the components within the & ...

Modify the layout of a JSON data structure

Here is an example of an array: let array = [ {1: { "date": "2014-04-23 00:00:00", "volumetrie": "22458" }}, {2: { "date": "2014-05-02 00:00:00", "volumetrie": "30585" }}, {3: { "date" ...

Every page on Nextjs displaying identical content across all routes

I recently deployed a Next.js app using docker on AWS infrastructure. While the index page (/) loads correctly, I've noticed that the content of the index is also being loaded for every other route, including api routes, as well as the JavaScript and ...

Not adhering to directive scope when transclusion is used, despite explicit instructions to do so

Trying to use a transcluding directive within another controller, but the inner scope isn't being redefined as expected. Despite trying different methods, I can't seem to figure out what's going wrong. The simplified code looks like this: ...

Extract the color from the most prominent element in the viewport

I'm working on a button that will take the user to the bottom of the page, and I want the background color of the button to match the color of the first element that touches the viewport. The button is functioning properly, but I'm having trouble ...

Avoid assigning a class name to child elements if both the parent and child elements already have inline background colors

I have a challenge where I need to assign a random class name to elements that have an inline background color. The additional condition is that if both the parent and child elements have inline background colors, the child element should not receive the c ...

Correctly align the div on the screen as the viewport is scrolled

I am currently working on a parallax website where the sliders are designed to slide from the left and align within the viewport as the user scrolls. However, I have encountered an issue where multiple scroll actions are required for the slide to align pro ...

What causes the "undefined" error in Node.js when using a

Currently, I am utilizing the node-craigslist package for scraping listings from craigslist. However, I have encountered an issue when processing the results. client .search(options, '') .then((listings) => { listings.forEach((listing ...

Adapt your content to match the current slide of the dynamic Bootstrap Carousel

I recently implemented the basic carousel from the bootstrap website into my web application and encountered a challenge. I want to adjust the content on my site based on the active slide of the carousel... is this achievable? My goal is to display div On ...

Utilizing HTML5 canvas to extract pixel data from an image loaded from an external source

When it comes to security reasons, doing it directly may not be feasible. Nevertheless, there are rumors circulating about certain image-hosting platforms that permit the use of their images in a comparable way (could Google Picasa be one?). I might be mis ...

Exploring Shadertoy's Visual Magic with THREE.js

I am currently attempting to implement this shader on a canvas using THREE.js: . The function I am using usually works for simpler shaders, but for this one, I might need to save the floats as uniforms. I am a bit stuck on this issue. Has anyone encounte ...

Sending data from configuration to factory in AngularJS and UI Router

Trying to perform a search in an http call with a dynamic value based on the current view. The factory setup is as follows: .factory('SearchService', ['$http','$filter', function($http, $filter) { var service = { get ...

What is the reason for future::future() not being compatible with dbAppendTable in a Shiny application?

One option is to utilize the future() function for performing side effects, such as saving a file: library(promises) library(future) plan(multiprocess) future({write.csv(mtcars,"mtcars.csv")}) However, this approach cannot be applied when making a databa ...

What is the process for granting a user the admin role within a company?

In the process of developing a Rest API using express, I have implemented a middleware to verify if a user is an admin or not. This raises the question of how companies typically designate a new user as an admin. Do they manually edit the database record ...

Utilize the keyboard's vertical arrows to adjust values as needed

Implement the functionality to increase and decrease the value in a label or p tags using the onkeydown and onkeyup events, without requiring a textbox input. I have come across numerous examples, but they all rely on textboxes. I am looking for a soluti ...

Adapting the Three.js displacement map shader to incorporate all RGB values instead of solely relying on the red

My goal is to enhance the precision of the displacement map by using an rgba texture to display displacement values with 32 bits accuracy instead of the default 8 bits in three.js. I am working on visualizing a flooding scenario and need to observe minute ...

Methods for applying multiple styles within a div using the Document Object Model

Is there a way to add multiple style attributes using DOM `setAttribute` in JavaScript? I've tried doing it but it doesn't seem to work. Can someone provide guidance on how to achieve this? var modify = document.getElementById('options&apo ...