javascript - 如何在 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' 时没有出现任何结果。
解决方案
你在像这样渲染 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>
根据要求进行一些更改.!!!
推荐阅读
- matlab - 在 MATLAB 上画箭头和画圈
- php - 电报机器人 - sendMessage 文本
- python - 如何在 python tkinter 中将一个函数的数组用于另一个函数?
- python-3.x - Asyncios await reader.read() 一直在等待
- javascript - 坚持尝试复制某个 CSS 转换(向下滚动时移动到页面底角并得到修复的 CTA 按钮)
- python - seaborn和plotly中密度等高线图的差异
- php - Sendgrid 电子邮件批量无法发送 PHP
- laravel - 如何在 Laravel 中使用 SwiftMailer 获取 SMTP 会话错误
- c++ - 为什么有些例子使用“endl”而不是“\n”?
- python - Python Flask getlist of checkboxes返回空列表