如何解决Discord.js,异步并等待
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()),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
和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()),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
兑现承诺就像将其后的内容视为then
内部一样,其中解析的值是await
ed表达式返回的值。对承诺的拒绝(.catch()
被转换为可以try{...}catch{...}
编辑的异常。
知道了这一点,您通过打电话来做什么
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。