Discord.js, async and await


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都返回一个promise

首先让我重构您的两个混合了promiseasync/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.');
}
};

正如您所看到的,对promise执行await就像将其后面的内容视为then内部的内容,其中解析的值是awaited表达式返回的内容。承诺的拒绝(.catch()(被转换为一个例外,可以是try{...}catch{...}ed.

知道了这一点,你打电话给是在做什么

getNumberOfQuestions();
getDifficulty();

异步调用这两个函数,而无需等待返回的promise结算。相反,您可能想做的是在调用第二个之前先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

最新更新