【问题标题】:Discord.js, async and awaitDiscord.js,异步和等待
【发布时间】:2020-12-05 08:21:50
【问题描述】:
const getNumberOfQuestions = async () => {
    await this.channel.send('How many questions should I ask? (1-10)')
        .then(async message => {
            await this.channel.awaitMessages(message => message.author.id === this.owner && !isNaN(parseInt(message.content)),  { max: 1, time: 15000 })
                .then(collected => {
                    this.channel.send(`You asked for ${collected.first().content} questions.`);
                    return parseInt(collected.first().content);
                })
                .catch(collected => {
                    this.channel.send('You did not tell me how many questions you wanted. Ending the quiz.');
                });
        });
};

const getDifficulty = async () => {
    await this.channel.send('What difficulty would you like: easy, medium, hard?')
        .then(message => {
            this.channel.awaitMessages(message => message.author.id === this.owner && ['easy', 'medium', 'hard'].includes(message.content.toLocaleLowerCase()),  { max: 1, time: 15000 })
                .then(collected => {
                    this.channel.send(`You asked for ${collected.first().content} difficulty.`);
                    return collected.first().content;
                })
                .catch(collected => {
                    this.channel.send('You did not tell which difficulty you wanted. Ending the quiz.');
                });
        });

};
getNumberOfQuestions();
getDifficulty();

使用上面的代码,我不希望在调用该函数时继续执行。我显然不了解承诺,等待有人可以帮助我吗?

.send.awaitMessages 都返回一个承诺

【问题讨论】:

  • 您无法控制执行流程。使用async-await,您唯一可以确定的是,代码 afterawait 在等待表达式的结果未返回之前不会执行
  • “我不希望执行在被调用时继续通过这个函数”到底是什么意思?
  • Ivan,此功能要求用户选择一些问题。然后,我有更多功能可以向需要输入的用户提出其他问题。目前,所有问题同时触发。我想以某种方式等到第一个完成,然后问下一个等等。
  • 在这种情况下您可能需要的东西称为锁,它可以防止多个流同时进入同一个关键部分。 stackoverflow.com/questions/34524/what-is-a-mutex
  • 我们没有看到询问您希望串行而不是并行的其他问题的代码。请发mcve?

标签: javascript asynchronous async-await discord.js


【解决方案1】:

首先让我重构您的两个混合有promises 和async/await 的过程,以便它们具有等价的async/await

const getNumberOfQuestions = async () => {
    const message = await this.channel.send('How many questions should I ask? (1-10)');
    try {
        const collected = await this.channel.awaitMessages(message => message.author.id === this.owner && !isNaN(parseInt(message.content)),  { max: 1, time: 15000 });
        this.channel.send(`You asked for ${collected.first().content} questions.`);
        return parseInt(collected.first().content);
    } catch(collected) {
        this.channel.send('You did not tell me how many questions you wanted. Ending the quiz.');
    }
};

const getDifficulty = async () => {
    const message = await this.channel.send('What difficulty would you like: easy, medium, hard?');
    try {
        const collected = await this.channel.awaitMessages(message => message.author.id === this.owner && ['easy', 'medium', 'hard'].includes(message.content.toLocaleLowerCase()),  { max: 1, time: 15000 });
        this.channel.send(`You asked for ${collected.first().content} difficulty.`);
        return collected.first().content;
    } catch(collected) {
        this.channel.send('You did not tell which difficulty you wanted. Ending the quiz.');
    }
};

如您所见,await 在 promise 上执行就像将其后面的内容视为 then 中的内容,其中解析的值是 awaited 表达式返回的值。 Promise 的拒绝 (.catch()) 被转换为异常,可以是 try{...}catch{...}ed。

通过调用知道这一点,你在做什么

getNumberOfQuestions();
getDifficulty();

正在异步调用这两个函数 - 无需等待返回的承诺解决。您可能想要做的是在调用第二个之前await 第一个结束。像这样:

await getNumberOfQuestions();
await getDifficulty();

但是,await 关键字仅在 async function 中才有意义,因此您可以这样做:

(async()=>{
    await getNumberOfQuestions();
    await getDifficulty();
})();

关于异步函数的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

【讨论】:

  • 感谢您抽出宝贵时间来做这件事。我现在理解更好的承诺、异步和等待!
猜你喜欢
  • 2021-04-25
  • 1970-01-01
  • 2017-04-17
  • 2018-11-29
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 2016-07-07
  • 2016-03-25
相关资源
最近更新 更多