我想将两个猫鼬查询称为“并行”,并将两个查询的返回数据传递给客户端。
//both queries should be called parallel, not one after another
//query 1
PaperModel.find().then((papers) => {
});
//query 2
ConferenceModel.find().then((conferences) => {
});
//this function should only be called when both the
//queries have returned the data
res.render('Home', {
Papers: papers
Conferences: conferences
});
我尝试查看this,但效果不佳。谢谢
最佳答案
如果PaperModel.find()和ConferenceModel.find()返回诺言,您可以在下面的代码中使用类似的东西:
//query 1
const papers = PaperModel.find();
//query 2
const conferences = ConferenceModel.find();
Promise.all([papers, conferences]).then((values) => {
res.render('Home', {
Papers: values[0]
Conferences: values[1]
});
})
以及带有带有异步等待语法的包装功能的另一个选项
const getData = async () => {
const papers = PaperModel.find();
const conferences = ConferenceModel.find();
const values = await Promise.all([papers, conferences]);
res.render('Home', {
Papers: values[0]
Conferences: values[1]
});
}