我编写了这段代码,但我无法运行我的机器人,我也不知道为什么。
if (command === 'await') {
let msg = await message.channel.send("Vote!");
await msg.react(agree);
await msg.react(disagree);
const reactions = await msg.awaitReactions(reaction => reaction.emoji.name === agree || reaction.emoji.name === disagree, {
time: 15000
});
message.channel.send(`Voting complete! \n\n${agree}: ${reactions.get(agree).count-1}\n${disagree}: ${reactions.get(disagree).count-1}`);
}
SyntaxError: await is only valid in async function
答案 0 :(得分:2)
如前所述,await只能在异步函数中使用。因此,如果此代码在函数内部,请使该函数异步。例如,如果周围的函数如下所示:
function doStuff() {
if(command === 'await'){
let msg = await message.channel.send("Vote!");
await msg.react(agree);
await msg.react(disagree);
const reactions = await msg.awaitReactions(reaction => reaction.emoji.name === agree || reaction.emoji.name === disagree, {time:15000});
message.channel.send(`Voting complete! \n\n${agree}: ${reactions.get(agree).count-1}\n${disagree}: ${reactions.get(disagree).count-1}`);
}
}
将其更改为此:
async function doStuff() { // <--- added async
if(command === 'await'){
let msg = await message.channel.send("Vote!");
await msg.react(agree);
await msg.react(disagree);
const reactions = await msg.awaitReactions(reaction => reaction.emoji.name === agree || reaction.emoji.name === disagree, {time:15000});
message.channel.send(`Voting complete! \n\n${agree}: ${reactions.get(agree).count-1}\n${disagree}: ${reactions.get(disagree).count-1}`);
}
}
如果此代码不在函数中(即,它位于脚本的最高作用域),则需要将其放在一个中。如果需要,它可以是立即调用的功能
(async function () {
if (command === 'await') {
const msg = await message.channel.send('Vote!');
await msg.react(agree);
await msg.react(disagree);
const reactions = await msg.awaitReactions(reaction => reaction.emoji.name === agree || reaction.emoji.name === disagree, { time: 15000 });
message.channel.send(`Voting complete! \n\n${agree}: ${reactions.get(agree).count - 1}\n${disagree}: ${reactions.get(disagree).count - 1}`);
}
})();