我试图在node.js的帮助下创建一个不和谐的机器人,其中我需要调用一个函数,这个函数可能会返回不和谐的API错误,我这样处理它们
interaction.user.send("Hi")
.catch(() => {return interaction.reply("...");
console.log("shouldnt run if an error accured")
但是,每当API错误准确时,返回语句不像通常那样停止代码执行。当异常准确时,如何阻止此代码中的console.log语句执行?
发布于 2021-12-22 18:29:27
js是异步的,因此它将API的请求放入执行队列(而不是等待api的响应)并继续执行,这就是即使发生错误也运行控制台语句的原因。
interaction.user.send("Hi")
.then(() => {
// do whatever you want when it succeed
})
.catch((error) => {
// handle error
});
您也可以签出异步等待相同的。
发布于 2021-12-23 19:34:18
正如@ParthPatel所指出的,interation.user.send()
正在返回一个可能不会在错误时立即被拒绝的承诺。像您的console.log()
这样的语句将在错误发生并被捕获之前运行。
然而,现在有了可以使用的异步等待语法,这可能会帮助您简化代码,这取决于您要做的是什么。
try {
await interaction.user.send("Hi");
console.log('Shouldn\'t run if error occurred.');
} catch(e) {
interaction.reply('...');
}
请注意,您只能在一个await
函数中使用async
函数,声明如下:
async function doSomething() {
// Do something here...
}
您可以在这里找到更多信息:等待
https://stackoverflow.com/questions/70457064
复制相似问题