【问题标题】:Javascript - Call two async functions parallel and pass both results to a third oneJavascript - 并行调用两个异步函数并将两个结果传递给第三个
【发布时间】:2019-05-02 22:44:19
【问题描述】:

我想调用两个猫鼬查询“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,但没有搞定。谢谢

【问题讨论】:

  • 就这么简单await Promise.all([someCall(), anotherCall()]);你没得到什么?你尝试了什么?

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-02-07
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 2014-12-10
    • 2021-03-15
    • 1970-01-01
    • 2021-06-25
    • 2016-05-23
    相关资源
    最近更新 更多