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

TypeScript中MongoDB异步查询内变量修改无法同步到外部的问题求助

问题原因

你遇到的核心问题是异步操作的执行顺序:QuizModel.findById是异步方法,返回Promise,你的代码里用forEach遍历的时候,forEach不会等待每个异步任务的then回调执行完毕,就直接走到了函数末尾的return finalPoint,这时候then里的累加逻辑还没运行,所以返回的是初始值0。

解决方案

把函数改成async/await风格,用Promise.all等待所有异步查询完成后再计算最终分数,代码如下:

import { GraphQLError } from 'graphql';
import QuizModel from "../../src/models/helper/quiz";

const quizPoints = async (params: {
  data: Array<{ quizID: string; answer: string }>
}) => {
  try {
    // 把每个答题项转换成异步查询的Promise,返回1(答对)或0(答错)
    const pointPromises = params.data.map(async (obj) => {
      const quiz = await QuizModel.findById(obj.quizID);
      if (!quiz) {
        throw new GraphQLError("No quiz found", {
          extensions: {
            code: "BAD_USER_INPUT",
            invalidArgs: obj.quizID
          }
        });
      }
      return obj.answer === quiz.answer ? 1 : 0;
    });

    // 等待所有异步操作完成,得到每个题目的得分数组
    const points = await Promise.all(pointPromises);
    // 累加所有得分
    return points.reduce((total, point) => total + point, 0);
  } catch (error) {
    // 统一抛出错误
    throw error;
  }
};

// 调用async函数需要用await或者.then
(async () => {
  const x = await quizPoints({
    data: [
      {
        "quizID": "something",
        "answer": "1"
      },
      {
        "quizID": "something2",
        "answer": "2"
      }
    ]
  });
  console.log(x);
})();
关键改动说明
  • 把quizPoints改为async函数,允许内部使用await等待异步操作
  • 用map替代forEach:map会返回一个Promise数组,每个Promise对应一个题目的得分判断
  • Promise.all(pointPromises):等待所有异步查询完成,确保所有得分都计算完毕再进行累加
  • 错误处理移到try/catch块中,统一捕获并抛出,避免在每个回调里单独处理
  • 调用quizPoints时必须用await(需要在async函数中)或者.then(),因为async函数返回的是Promise

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 04:22:53