【问题标题】:discord.js bot await is only valid in async functiondiscord.js bot await 仅在异步函数中有效
【发布时间】:2020-12-23 20:28:14
【问题描述】:

我不知道我可以把异步放在哪里。请帮帮我。我有一个日志等待仅在异步函数中有效

const args = message.content.split(' ');
const command = args.shift().toLowerCase();

if (command === '.eval') {
 // Put your userID here
 if (message.author.id !== '505034363914682368') return;

 let evaled;
 try {
  evaled = await eval(args.join(' '));
  message.channel.send(inspect(evaled));
  console.log(inspect(evaled));
 } catch (error) {
  console.error(error);
  message.reply('there was an error during evaluation.');
 }
}

【问题讨论】:

  • 是的,关键字 await 仅在 async 定义的函数内部可用:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 基本上,async/await 是 Promises 之上的糖/抽象。我建议您提高对 JavaScript 中的 Promise 的了解,以便能够更好地理解 async/await 如何工作的上下文。
  • 在 JS 中 eval() 不需要 await

标签: javascript node.js async-await discord.js


【解决方案1】:

您必须确保您的 message 函数是异步的。

client.on('message', async (message) => {
//                   ^^^^^

【讨论】:

    【解决方案2】:

    当然,await 只适用于异步函数。您可以使用 .then(callback) 代替 async-await 或将整个代码转换为 IIFE(立即调用函数表达式),并将函数声明为异步函数并在其中使用 await。

    【讨论】:

      猜你喜欢
      • 2020-09-07
      • 2021-08-10
      • 1970-01-01
      • 2019-09-12
      • 1970-01-01
      • 2022-06-18
      • 2020-08-13
      • 2020-04-15
      • 2019-06-14
      相关资源
      最近更新 更多