如何让Discord Bot等待Promise完成后再发送消息?
Hey there, let's sort out that "Cannot send empty message" error you're hitting with your Discord Bot.
问题根源
This error pops up because your message-sending logic runs before your target function finishes fetching data. Functions that make network requests (like your axios call) are asynchronous—they don't block the rest of your code from running. So when you try to send the message right after calling the function, the function hasn't had time to return any content yet, hence the empty message.
修复方案:用async/await等待异步操作完成
You already mentioned you fixed this by making your exported function async and using await with the axios request—great call! Let's break down exactly how that works with code examples to make it clear:
错误的写法(导致空消息)
// 目标函数:没有处理异步逻辑,直接返回undefined function getTargetContent() { axios.get("your-target-url") .then(res => res.data); } // Discord消息处理逻辑 client.on("messageCreate", message => { const content = getTargetContent(); message.channel.send(content); // content还是undefined,发送空消息 });
修复后的正确写法
// 把目标函数改成async函数,内部用await等待axios请求 async function getTargetContent() { const response = await axios.get("your-target-url"); return response.data; } // 消息处理函数也要标记为async,这样才能用await client.on("messageCreate", async message => { try { // 等待目标函数返回内容后再继续 const content = await getTargetContent(); if (content) { message.channel.send(content); // 现在有内容了,正常发送 } else { message.channel.send("抱歉,没能获取到内容😅"); } } catch (err) { // 捕获请求失败的情况,避免Bot崩溃,同时给用户反馈 message.channel.send(`获取内容出错了:${err.message}`); } });
额外注意点
- Any function that uses
awaitmust be marked withasync—that includes your Discord event handler here. - Wrapping everything in a
try/catchblock is crucial for handling network errors or unexpected issues, so your Bot doesn't crash silently and users get useful feedback.
内容的提问来源于stack exchange,提问作者9349u8u3guhir

