【问题标题】:Who to Render Multiple fetch function in ejs谁在 ejs 中渲染多个 fetch 函数
【发布时间】:2022-02-17 17:10:13
【问题描述】:

多个获取 res 渲染功能,嘿,我正在尝试在 ejs 中执行多个 res 渲染功能,但我的数据丢失是他们的任何修复

app.get("/" , function(req,res){
    fetch(`${domain}/popular`)
      .then(res => res.text())
      .then(datap => {
        res.render('home',{datap : JSON.parse(datap)});})
    fetch(`${domain}/recent-release`)
      .then(res => res.text())
      .then(datar => {
        res.render('home',{datar : JSON.parse(datar)});})
})

我想做多个 fetch 函数,但是 datar 正在替换 datap

【问题讨论】:

    标签: node.js express ejs


    【解决方案1】:

    为这两个请求转换function to async、await,仅在它们完成后渲染。 (我还冒昧地使用了异步 res.json() 解析器而不是 res.text() + JSON.parse。)

    app.get("/", async function(req, res) {
      const res1 = await fetch(`${domain}/popular`);
      const datap = await res1.json();
      const res2 = await fetch(`${domain}/recent-release`);
      const datar = await res2.json();
      res.render("home", { datap, datar });
    });
    

    (未来的优化可能是使用Promise.all() 并行执行两个请求。)

    【讨论】:

      猜你喜欢
      • 2021-02-26
      • 2016-09-14
      • 1970-01-01
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      • 2020-06-23
      • 2021-03-16
      • 1970-01-01
      相关资源
      最近更新 更多