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

Node.js中如何等待event.once()触发后再执行switch逻辑?

解决方案

你的核心问题是**getAction是异步函数,直接赋值给action得到的是Pending状态的Promise而非最终操作结果**,导致switch语句提前执行。结合Node.js+socket.io+express的技术栈,无需额外插件,通过异步函数改造就能解决问题。

改造步骤:

  1. 将_bettingPhase声明为async函数,允许内部使用await等待Promise兑现
  2. 用await获取getAction的真实返回值,再赋值给玩家的action属性
  3. 修复switch语句的case穿透问题(每个case末尾添加break,否则执行完raise会继续执行call的逻辑)

改造后的完整代码:

async _bettingPhase() {
    let index = 0;
    const pArray = this._playerArray;
    let standingBet = 0;

    async function getAction(index, playerArray) {
        const myPromise = new Promise(resolve => {
            playerArray[index].id.once('turn', (turn) => {
                resolve(turn);
            });
        });
        const turn = await myPromise;
        console.log('getAction run');
        return turn;
    }

    // 等待getAction完成,拿到玩家的真实操作指令
    this._playerArray[index].action = await getAction(index, pArray);

    switch(this._playerArray[index].action) { 
        case 'raise': 
            this._playerArray[index].money -= this._playerArray[index].amount + standingBet; 
            standingBet = this._playerArray[index].amount;
            break; // 阻止case穿透到call逻辑
        case 'call': 
            this._playerArray[index].money -= this._playerArray[index].amount;
            break; // 阻止后续无意义的代码执行
    }
}

额外注意事项:

  • 调用_bettingPhase的地方也要适配异步逻辑:如果在普通函数中调用,需要用this._bettingPhase().then(...)处理后续流程;如果调用方也是类方法,建议同样声明为async函数并使用await调用
  • 原代码中使用var声明变量,建议替换为let/const提升代码作用域稳定性
  • 未修复的case穿透会导致玩家选择raise后额外执行call的扣钱逻辑,这完全不符合扑克规则,必须修正

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 06:35:51