首页 > 解决方案 > 如何在 ejs 文件中使用 await?

问题描述

这不是重复的。我希望能够在我的 ejs 文件中持续执行等待,但我有一个著名的错误:SyntaxError: await is only valid in async function in C:\Users\...\dashboard.ejs while compiling ejs 你能向我解释它是如何工作的以及如何修复我的代码吗?:

应用程序.js


  let ejsOptions = {
    // delimiter: '?', Adding this to tell you do NOT use this like I've seen in other docs, does not work for Express 4
    async: true
  };

  // We set out templating engine.
  app.engine("html", async (path, data, cb) => {
    try{
      let html = await ejs.renderFile(path, data, ejsOptions);
      cb(null, html);
    }catch (e){
      cb(e, '');
    }
  });


  app.get("/dashboard", checkAuth, async (req, res) => {

    await renderTemplate(res, req, "dashboard.ejs", { perms: Discord.Permissions });
  });

仪表板.ejs:



  <%
  let results;
 
    results = await bot.shard.broadcastEval(`this.guilds.cache.get('${guild.id}')`);
  
  console.log(results.id)

  if (results) {
     %>
    <a class="button is-success has-text-centered" href="/dashboard/<%= guild.id %>">Settings</a>
  <% } else { %>
    <a class="button is-primary has-text-centered" href="<%= `https://discordapp.com/oauth2/authorize?client_id=${bot.user.id}&scope=bot&guild_id=${guild.id}&response_type=code&redirect_uri=${encodeURIComponent(`${bot.config.domain}${bot.config.port == 80 ? "" : `:${bot.config.port}`}/callback`)}` %>">Invite</a>
  <% } 

    %>
   <% }); %>
<%- include("partials/footer") %>
</section>

我尝试了很多方法,但是当我尝试使用 'if' 'else' 时没有出现任何结果。

标签: javascriptnode.jsejs

解决方案


你在像这样渲染 ejs 文件之前得到结果数据。

应用程序.js

app.get("/dashboard", checkAuth, async (req, res) => {
    const data = await bot.shard.broadcastEval(`this.guilds.cache.get('${guild.id}')`);
    renderTemplate(res, req, "dashboard.ejs", { perms: Discord.Permissions, data });
});

仪表板.ejs

.... your code.....

  if (data != undefined) || data != null) {
     %>
    <a class="button is-success has-text-centered" href="/dashboard/<%= guild.id %>">Settings</a>
  <% } else { %>
    <a class="button is-primary has-text-centered" href="<%= `https://discordapp.com/oauth2/authorize?client_id=${bot.user.id}&scope=bot&guild_id=${guild.id}&response_type=code&redirect_uri=${encodeURIComponent(`${bot.config.domain}${bot.config.port == 80 ? "" : `:${bot.config.port}`}/callback`)}` %>">Invite</a>
  <% } 

    %>
   <% }); %>
<%- include("partials/footer") %>
</section>

根据要求进行一些更改.!!!


推荐阅读