等待发送数据,直到所有Promise都得到解决

时间:2018-03-15 00:57:42

标签: javascript express promise knex.js

我正在尝试两次查询我的数据库。我能够记录我想要的数据,但我无法发送该数据,因为承诺无法及时解决。我想知道我是如何做到这一点的,所以我等到所有的承诺都解决后才发送数据。谢谢你的帮助。

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

1 个答案:

答案 0 :(得分:0)

试试这个

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);
        });
});
相关问题