如何在创建嵌入之前等待用户输入

时间:2020-09-20 16:36:59

标签: discord discord.js

我对下面的代码有一个快速的疑问。我正在尝试收集用户输入以建立嵌入,但是它正在立即创建嵌入,而不是等待awaitMessage完成。无论如何有解决的办法,这是什么原因呢?我知道我可以将嵌入代码放在.then块中,但是我想将其保留在外面,因为我将收集其他用户输入。

感谢您的帮助!

message.author.send(
 'Lets get to work!\nPlease enter the title of your event. (Must be shorter than 200 characters)'
);
message.channel
 .awaitMessages(
  (response) =>
   response.author.id === message.author.id && response.content.length < 10,
  {
   max: 1,
   time: 10000,
   errors: ['time'],
  }
 )
 .then((collected) => {
  message.author.send(`I collected the message : ${collected.first().content}`);
  let title = collected.first().content;
 })
 .catch(() => {
  message.author.send('No message collected after 10 seconds.');
 });

const eventEmbed = new Discord.MessageEmbed()
 .setColor('RANDOM')
 .setTitle(title)
 .setAuthor(message.author.username)
 .setDescription('help')
 .setImage();
message.channel.send(eventEmbed);

1 个答案:

答案 0 :(得分:0)

如果您不想在回调中继续,可以将其放在函数中。

const sendSomething = () => {
  message.author.send(
    "Lets get to work!\nPlease enter the title of your event. (Must be shorter than 200 characters)"
  );
  message.channel
    .awaitMessages(
      (response) =>
        response.author.id === message.author.id &&
        response.content.length < 10,
      {
        max: 1,
        time: 10000,
        errors: ["time"],
      }
    )
    .then((collected) => {
      message.author.send(
        `I collected the message : ${collected.first().content}`
      );
      let title = collected.first().content;
    })
    .catch(() => {
      message.author.send("No message collected after 10 seconds.");
    });
};

await sendSomething()

// do something after

代码段演示:

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => resolve('Success!'), 2000); // delay 2 seconds to simulate awaiting a message
});

promise1.then((res) => {
  console.log(res);
});

console.log('This will execute before, even though it is positioned after');

const newFunction = () => { // create it in a function
  const promise1 = new Promise((resolve, reject) => {
    setTimeout(() => resolve('Success!'), 2000); // delay 2 seconds to simulate awaiting a message
  });

  return promise1.then((res) => { // return the promise callback
    console.log(res);
  });
};

// both `.then()` and `await` will work
newFunction().then(() => console.log('This will execute after, *and* is positioned after'));