Javascript-并行调用两个异步函数,并将两个结果都传递给第三个

时间:2018-11-30 18:51:31

标签: javascript node.js asynchronous mongoose es6-promise

我想将两个猫鼬查询称为“ Parallel ”,并将两个查询的返回数据传递给客户端。

//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,但效果不佳。谢谢

1 个答案:

答案 0 :(得分:0)

如果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]
  });
}