Async方法未等待await执行返回undefined,规划扑克开发问题排查
问题原因与修复方案
核心疏漏点
- 你存在的最大问题是
checkCoffeeTimeout作为async函数没有显式返回任何值:你在.then()回调中返回的coffeeVotes >= half只会作为.then返回的Promise的 fulfilled 值,没有被外层的checkCoffeeTimeout函数返回,所以调用后拿到的结果就是undefined。你觉得方法没有等待this.updateDBData()执行完成属于误解,await已经正常等待了异步操作执行结束,只是没有返回结果导致你误以为没有等待。 - 额外优化点:混用async/await和.then链式调用会提升逻辑理解成本,也更容易出现返回值遗漏的问题,建议统一用await写法更清晰。
- 你的
updateDBData方法返回的是Mongoose的Query对象,本身是thenable的,不需要额外修改,await可以正常等待它执行完成。
修复后的代码
方案1:保留原有.then结构,补充return语句
async checkCoffeeTimeout() { let coffeeVotes = 0; // 这里添加return,把整个await的Promise结果返回出去 return await this.updateDBData() .then(response => { this.dbData = response[0]; let feature = this.dbData.features[this.featurePointer]; let half = 1; if(feature !== undefined) // Waiting state has no features yet { half = feature.votes.length / 2 feature.votes.forEach(vote => vote.value == -1 ? coffeeVotes++ : ''); } return coffeeVotes >= half; }); }
方案2:统一用async/await写法,移除.then链式调用(更推荐)
async checkCoffeeTimeout() { let coffeeVotes = 0; // 直接await拿到数据库响应 const response = await this.updateDBData(); this.dbData = response[0]; let feature = this.dbData.features[this.featurePointer]; let half = 1; if(feature !== undefined) { half = feature.votes.length / 2; feature.votes.forEach(vote => vote.value === -1 && coffeeVotes++); } // 直接返回计算结果 return coffeeVotes >= half; }
额外逻辑提示
如果你的业务要求是严格过半数(大于50%),当前的>= half逻辑在投票人数为奇数的时候会自动适配,比如3人投票时half=1.5,大于等于2才满足要求,符合过半数规则;如果你的判定规则是「至少一半」,当前逻辑也可以正常运行。
内容的提问来源于stack exchange,提问作者SeasideCoding
相关产品推荐
相关产品推荐

