1

I don't know whether it is async problem so that sometimes the result had no product data but only type data. However, sometimes it will have both data.

My setup: Node JS, Express, Mongoose

router.get('/', function (req, res, next) {
var data = {};
Product.find().limit(4).populate({path: 'region_id', model: Region})
    .then(function (doc) {
        data.product = doc;
    });
Type.find()
    .then(function (doc) {
        data.type = doc;
    });

res.render('index', {title: 'Home', items: data});
});

If I am correct then how to make sure all the find() function is executed before running render().

Thanks!

1 Answer 1

3

Because both asynchronous operations return Promises, you should use Promise.all, which will resolve when both complete. There's no need for an outer data object, just use the values of the resolved promises directly. Also, don't forget to handle errors with catch when using Promises:

router.get('/', function (req, res, next) {
  Promise.all([
    Product.find().limit(4).populate({path: 'region_id', model: Region}),
    Type.find()
  ])
    .then(([product, type]) => {
      res.render('index', {title: 'Home', items: { product, type } });
    });
    .catch((err) => {
      // handle errors
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.