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