异步/等待 Discord.js Node.js Javascript JS

时间:2021-01-20 23:44:36

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

嘿,我希望有人能帮助我解决我的问题。

下面的代码应该输出:

你好 世界! 再见!

但它不会等待第二行被执行。

所以输出是 你好 再见! 世界!

const Discord = require("discord.js");
const config = require("./config.json");
const client = new Discord.Client();
const prefix = "02";

client.on("message", async message => {
    if (message.author.bot) return;
    if (!message.content.startsWith(prefix)) return;

    const commandBody = message.content.slice(prefix.length);
    const args = commandBody.split(' ');
    const command = args.shift().toLowerCase();

    if (command === "help" || command === "h" || command === "hilfe"){

    console.log("Hello");
    await setTimeout(() => { console.log("World!"); }, 2000);
    console.log("Goodbye!");
    }

});

client.login(config.BOT_TOKEN);

1 个答案:

答案 0 :(得分:1)

您需要承诺 setTimeout 逻辑,以便 await 可以使用它。考虑这个 sleep 函数实现。

function sleep(timeInMs) {
  return new Promise(resolve => {
    setTimeout(resolve, timeInMs);
  });
}

// usage
async message => {
  // …
  console.log("Hello");
  await sleep(2000);
  console.log("World!");
  console.log("Goodbye!");
}