javascript - 如何确保在 Node JS 上的 render() 之前执行查询
问题描述
我不知道这是否是异步问题,因此有时结果没有产品数据而只有类型数据。但是,有时它会有两个数据。
我的设置: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});
});
如果我是正确的,那么如何确保在运行 render() 之前执行所有 find() 函数。
谢谢!
解决方案
因为两个异步操作都返回Promise
s,所以您应该使用Promise.all
,这将在两者都完成时解析。不需要外部data
对象,只需直接使用已解析承诺的值即可。另外,不要忘记catch
在使用 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
});
});
推荐阅读
- regex - 用正则表达式匹配多个字符串字符
- python-3.x - 我无法使用 scrapy.FormRequest 发出“POST”请求
- c# - 将 XML 文件加载和保存到 Listview
- iot - ESP12E WiFi 始终开启,即使它不应该开启
- javascript - 使用 javascript 将一个数字关联到每个链接 html
- pygame - 对齐对象并获取 pygame/turtle 游戏坐标的工具?
- c# - IBM.Data.DB2.Core 设置过程
- c# - 运行 asp.net Web 表单项目时找不到类型或命名空间名称
- excel - 在纸条上找一条直线
- javascript - 你好!如何使用正则表达式删除所有非数字字符,留下 ab3f4 // => 34