【发布时间】:2020-02-11 15:31:39
【问题描述】:
所以,我正在构建一个 Bot(专门用于 Discord),而且我对 JavaScript 和一般编码非常陌生。
我正在观看有关从区域命令中清除消息的教程(您告诉机器人要删除多少条消息,它会这样做。)
一切都很顺利,我在这个命令上工作了将近一个小时,在我保存并在我的 CMD 中运行“机器人”后,我收到了这个错误(显示在错误部分和预期结果区域)
基本上:
const fetched = await message.channel.fetchMessages({limit: args[0]});
SyntaxError: await 仅在异步函数中有效
但我很确定这是一个 async 函数,我对编码还是很陌生,所以我可能已经关闭它或其他什么,不确定。
仅供参考,在第 31 行,我以为我“打开”了 async 的东西,但也许我关闭了它。
我没有发送完整的代码。
由于我对编码还很陌生,所以我真的做不了太多。我确实添加了一个“;” (不带引号)解决了一个错误,但不是我要问的那个。
// Purge messages command.
if (msg.startsWith(prefix + 'PURGE')) { // COmmand checks like "!PING", but ``startWith`` because you'll be adding a number.
// Wrapping in an async because ``awaits`` only work in asyncs.
async function purge() {
message.delete(); // Deletes command trigger, to clean up the chat more fully.
//Now, we want to check if the user has the `Moderator` role.
if (!message.member.roles.find("name", "Moderator")) { // This checks to see if they DONT have that role (the "!" inverts the true/false)
message.channel.send('You need the Moderator role to use this command!');
return; // This returns the code, so the rest doesn't run.
}
}
// Check if the argument is a number.
if (isNaN(args[0])) {
// Posts that the message is NaN (not a number)
message.channel.send('Your argument was not a number. \n Usage: ' +
prefix + 'purge <amount>'); //\n turns into a new line.
// Stops the actions, so it doesn't start deleting messages.
return;
}
const fetched = await message.channel.fetchMessages({limit: args[0]}); // This takes the argument number.
预期结果:Bot 开启并删除大量指定消息。
完整的错误信息:
C:\Users\xxxx\OneDrive\Desktop\Xxxxx xxx\xxx.js:49 const fetched = await message.channel.fetchMessages({limit: args[0]}); // 这需要参数编号。
SyntaxError: await 仅在异步函数中有效 在 Module._compile (internal/modules/cjs/loader.js:723:23) 在 Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10) 在 Module.load (internal/modules/cjs/loader.js:653:32) 在 tryModuleLoad (internal/modules/cjs/loader.js:593:12) 在 Function.Module._load (internal/modules/cjs/loader.js:585:3) 在 Function.Module.runMain (internal/modules/cjs/loader.js:831:12) 启动时(内部/bootstrap/node.js:283:19) 在 bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
【问题讨论】:
-
它说
await仅在async函数内有效。它并不是说它是 FORasync函数。您在async函数之外调用await -
async function purge() {在if语句中声明的意义何在,它从未被调用过
标签: javascript asynchronous async-await syntax-error discord.js