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!
Because both asynchronous operations return Promise
s, 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
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.