TypeScript非async函数中等待Promise的问题求助
问题解决:async函数返回Promise导致判断失效
问题原因
async 函数调用后会返回一个Promise实例,而非直接返回函数内部的布尔值。你当前的代码中,!doesUserExist(message.author.id) 实际上是在判断Promise对象是否为“假值”,但Promise永远是真值,因此if语句内的逻辑永远不会执行。
解决方案
有两种方式正确处理async函数的返回值:
方案1:使用async/await(推荐,代码更简洁易读)
将messageCreate的回调函数改为async函数,通过await获取doesUserExist的实际返回值:
client.on("messageCreate", async (message) => { try { const userExists = await doesUserExist(message.author.id); if (!userExists) { // 发送自定义Discord消息等逻辑 message.channel.send("你尚未在数据库中注册,请完成注册后再操作!"); } } catch (error) { // 处理数据库查询可能出现的错误 console.error("检查用户存在性时出错:", error); message.channel.send("抱歉,当前无法验证你的身份,请稍后再试。"); } });
方案2:使用Promise的.then()方法
如果不想修改回调为async函数,可以通过.then()处理Promise的结果:
client.on("messageCreate", (message) => { doesUserExist(message.author.id) .then(userExists => { if (!userExists) { // 发送自定义Discord消息等逻辑 message.channel.send("你尚未在数据库中注册,请完成注册后再操作!"); } }) .catch(error => { console.error("检查用户存在性时出错:", error); message.channel.send("抱歉,当前无法验证你的身份,请稍后再试。"); }); });
可选优化:简化doesUserExist函数
可以直接返回判断结果,简化函数逻辑:
async function doesUserExist(user_id: string) { const userInfo = await database.GetUserInfo(user_id); return userInfo !== null; }
内容的提问来源于stack exchange,提问作者SebastiaanTheCoder
相关产品推荐
相关产品推荐

