You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript调用MongoDB查询后函数返回undefined问题求助

问题分析与修正方案

核心问题

你的函数始终返回undefined的原因很明确:

  • 外层CheckActiveGamesPlayer1函数没有任何返回语句,回调函数里的return仅属于回调本身,不会传递给外层函数。
  • 给回调加async完全无效,因为外层函数还是同步执行,根本没等待异步的数据库查询完成。

修正代码

把函数改成async/await风格,直接使用Promise版本的findOne(现代MongoDB驱动均支持Promise,无需回调):

async function CheckActiveGamesPlayer1(memberid) {
    console.log("3");
    try {
        const data = await db.findOne({ GuildID: guild.id, Player1: memberid });
        // 先处理未找到数据的情况,避免后续报错
        if (!data) {
            console.log("5");
            return true;
        }
        if (data.Ingame === true) {
            console.log("4");
            Embed.setDescription(`<@${memberid}> 正在进行对局,无法开始新游戏!`).setColor("RANDOM");
            await channel.send({ embeds: [Embed], ephemeral: true });
            return false;
        } else {
            console.log("5");
            return true;
        }
    } catch (err) {
        // 处理数据库查询出错的情况,避免程序崩溃
        console.error("查询数据库时出错:", err);
        // 可根据需求返回默认值或抛出错误
        return false;
    }
}

关键改动说明

  1. 给外层函数加async,使其成为异步函数,内部可通过await等待异步操作完成。
  2. 用await替代回调,直接获取findOne的结果,此时外层函数的return能正确返回布尔值。
  3. 增加try/catch处理数据库查询可能出现的错误,同时处理data为null(未找到匹配数据)的情况,避免data.Ingame触发报错。
  4. 给channel.send加await,确保消息发送完成后再返回结果(可选,但能保证流程顺序)。

使用注意

调用该函数时,必须用await或.then()获取返回值:

// 示例调用(需在async函数内执行)
const canStartGame = await CheckActiveGamesPlayer1(memberid);
if (canStartGame) {
    // 执行开始新游戏的逻辑
}

内容的提问来源于stack exchange,提问作者KittyCatCrafter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 23:05:20