Search code examples
javascriptexpresspromiseknex.js

Wait to send data until all Promises are resolved


I'm trying to query my database twice. I am able to log the data that I want but I am unable to send that data because the promise doesn't resolve in time. I am wondering how I can make it so that I wait till all the promises are resolved before I send the data. Thanks for any help.

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);
              });
});

Solution

  • Try this

    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);
            });
    });