异步方法返回undefined求助:调用者始终获取不到已填充结果
看起来你的问题有点奇怪——目标方法里明明已经把数组填充好并返回了,但调用方却拿到undefined。我帮你梳理几个可能的排查方向和解决方案:
1. 检查是否有未捕获的错误
虽然你的目标方法日志显示returnShares已填充,但如果在getShares执行过程中出现了未被捕获的错误,await会抛出这个错误,导致foundShares没有被赋值(如果没有try/catch的话,错误会被默默吞掉,看起来就像拿到了undefined)。
你可以在调用方加个try/catch看看:
groups.forEach(async group =>{ try { let foundShares = await group.getShares(); console.log("found shares ", foundShares) } catch (error) { console.error("获取Shares时出错:", error); } })
2. 确认getShares方法是否正确挂载
有时候Mongoose的methods挂载可能会出问题,比如你在定义schema之后才挂载方法,或者查询时用了lean()(会返回纯JSON对象,没有methods)。你可以在调用前先确认方法存在:
groups.forEach(async group =>{ console.log("getShares方法是否存在:", typeof group.getShares); // 应该输出"function" let foundShares = await group.getShares(); console.log("found shares ", foundShares) })
3. 替换forEach为for...of(避免异步循环的坑)
虽然这不是直接导致undefined的原因,但forEach对异步函数的支持不太友好——它不会等待每个异步回调完成,可能会导致日志顺序混乱,甚至让你误以为是foundShares为undefined。换成for...of会更稳妥:
async function processGroups() { for (const group of groups) { let foundShares = await group.getShares(); console.log("found shares ", foundShares) } } processGroups();
4. 简化getShares方法(去掉不必要的async)
你的getShares方法里没有任何异步操作,完全是同步逻辑,其实不需要定义为async函数。虽然async函数会把返回值包装成Promise,但有时候这种多余的包装可能会引发一些意想不到的问题(比如某些环境下的Promise处理异常)。你可以改成同步方法试试:
UserTaskGroupsSchema.methods.getShares = function () { console.log("start hasshares") let returnShares = []; let users = this._team.users; users.forEach( user=>{ if (user.shares) { user.shares.forEach( share=>{ if (share.groupId.toString() === this._id.toString()){ console.log("found share with groupid ") returnShares.push(share); } }); } }) console.log("Returning returnshares ", returnShares) return returnShares; }
调用的时候也不需要await了:
groups.forEach(group =>{ let foundShares = group.getShares(); console.log("found shares ", foundShares) })
以上几个方向应该能帮你定位到问题。我觉得最有可能的是未捕获的错误或者方法挂载的问题,先试试加try/catch和检查方法是否存在吧。
内容的提问来源于stack exchange,提问作者user11666430

