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

如何让代码等待Promise完成而非pending,获取客户端玩家操作?

问题分析与解决方法
  • 核心问题:你的getAction函数创建了Promise但没有返回它,导致await getAction(...)实际上是在等待undefined,自然不会暂停代码执行。这就是为什么代码直接继续执行,输出pending状态的Promise(你在函数内打印的那个),但action值为undefined。

  • 修复后的代码:
    给getAction添加返回语句,同时建议用once替代on监听事件——因为每个玩家回合应该只触发一次操作,once会在事件触发后自动移除监听,避免后续重复触发导致的意外问题:

    async _bettingPhase() {
        var index = 0;
        var pArray = this._playerArray;
    
        function getAction(index, playerArray) {
            // 返回创建的Promise,让await能正确等待
            return new Promise(function(resolve) {
                // 用once替代on,确保只监听一次turn事件
                playerArray[index].id.once('turn', (turn) => {
                    resolve(turn);
                });
            });
        }
    
        this._playerArray[index].action = await getAction(index, pArray);
        console.log(this._playerArray);
        console.log('bettingPhase finish');
    }
    
  • 修改说明:

    1. return new Promise(...)让getAction返回Promise实例,await才能正确等待该Promise变为resolved状态。
    2. 使用once替代on,可以避免同一玩家多次触发turn事件时重复resolve Promise的问题,保证每个回合只处理一次玩家操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 21:01:54