-1

Hey I hope someone can help me with my problem.

The following code should Output:

Hello World! Goodbye!

But it doesn`t wait for the second Line to be execute.

So the Output is Hello Goodbye! World!

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);
L L
  • 1
  • 4
    `await` keyword only works on promise. `setTimeout` does not return a promise, thus it won’t work. – hackape Jan 20 '21 at 23:49
  • alternatively, you can put all the `console.log` code inside your `setTimeout`. and take a look in this question [Combination of async function + await + setTimeout](https://stackoverflow.com/questions/33289726/combination-of-async-function-await-settimeout) – André Walker Jan 21 '21 at 00:49

1 Answers1

1

You need to promisify the setTimeout logic so that await can work with it. Consider this sleep function implementation.

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!");
}
hackape
  • 18,643
  • 2
  • 29
  • 57