await 仅在 bot 命令内的异步函数错误中有效

await is only valid in async function error inside a bot command

我写了这段代码,但我不能运行我的机器人,我不知道为什么。

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

正如它所说,await 只能在 async 函数中使用。因此,如果此代码在函数内部,请使该函数异步。例如,如果周围函数如下所示:

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}`);
  }
})();