【问题标题】:Await not waiting for previous code block to be executed等待不等待前一个代码块被执行
【发布时间】:2020-12-12 02:13:21
【问题描述】:

我正在尝试使用节点 js 制作一个不和谐的机器人,我正在尝试获取用户名作为响应,并且想在用户输入他/她的用户名后发送感谢信。但是这两条消息,询问用户名的文本和感谢您同时发送,请帮助。

module.exports = {
    name: 'create',
    description: "help page",
    async pls(bot,message,args){
       
      if(!args[2]){
          message.channel.send('Server nickname was not passed');
          return;
      }
      var details = {nickname:'',username:'',pass:'',ip:''};
      details.nickname = args[2];

      message.channel.send('Please check your private messages');
  
      await message.author.send('Enter your username (PLS enter in 30 seconds)') 
        .then((newmsg) => { 
          newmsg.channel.awaitMessages(response => response.content, {
          max: 1,
          time: 15000,
          errors: ['time'],
          })
          .then((collected) => {
            details.username = collected.first().content;
            console.log(details);
        
          })
          .catch(() => {
            newmsg.channel.send('time ran out');
          });
        })
      ;

      await message.channel.send('thanks');
      
        
         
        
        
        

    }
}

【问题讨论】:

  • 你不使用await .then():要么try/await/catch the promise,要么使用.then.catch,但不要同时使用.现在你在等待 then() 的结果,这没什么
  • 或许return newmsg.channel.awaitMessages .....

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


【解决方案1】:

首先,您不应该在同一行中使用awaitthen。两者都是用于返回 Promise 的函数的符号,并且都告诉代码等待该 Promise 返回。然后,如果您希望无论发生哪种情况都出现“谢谢”,您应该使用finally,它仅在出现 try 或 catch 块后运行。

也就是说,它应该是这样的:

await message.author.send('Enter your username (PLS enter in 30 seconds)');
messages.channel.awaitMessages(response => response.content, {
    max: 1,
    time: 15000,
    errors: ['time'],
}).then((collected) => {
    details.username = collected.first().content;
    console.log(details);
}).catch(() => {
     message.channel.send('time ran out');
}).finally(() =>{
     await message.channel.send('thanks');
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-22
    • 2020-06-14
    • 2018-05-20
    • 2019-02-16
    • 2015-06-02
    • 1970-01-01
    • 2021-07-30
    • 2020-09-28
    相关资源
    最近更新 更多