等待`.on()`被执行,而不是待定的?

huangapple go评论62阅读模式
英文:

Wait for .on() to be fulfilled, not pending?

问题

我的期望输出是让 this._playerArray[index].action 实际上包含玩家的动作。我希望编写 "await getAction()" 会停止我的代码运行。问题是,Promise 处于挂起状态,代码不等待它被履行就继续执行。

有没有办法编写代码,让我的代码等待 Promise 被履行,即等待从客户端发出的事件?请注意,代码运行得非常快,玩家没有机会输入任何内容。

下面的代码输出 "promise { }",玩家的动作是 "undefined",然后输出 "bettingPhase finish"。

    async _bettingPhase() {
        var index = 0;
        var pArray = this._playerArray;

        function getAction(index, playerArray) {
            var action = null;
            let myPromise = new Promise(function(resolve) {
                playerArray[index].id.on('turn', (turn) => {
                    resolve(turn);
                })
            });
            console.log(myPromise);
        }

        this._playerArray[index].action = await getAction(index, pArray);
        console.log(this._playerArray);
        console.log('bettingPhase finish');
    }
英文:

My desired output is for this._playerArray[index].action to actually have the player's action. I had hoped that writing "await getAction()" would stop my code from running. The problem is, the promise is pending and the code doesn't care to wait until it is fulfilled until moving on.

Is there any way to code this so that my code will wait until the promise is fulfilled, ie the event being emitted from the client side? Note that the code runs so fast that the player doesn't get to input anything.

The code below outputs "promise { <pending> }", the player's action is "undefined", then "bettingPhase finish"

    async _bettingPhase() {
		var index = 0;
		var pArray = this._playerArray;

		function getAction(index, playerArray) {
			var action = null;
		  let myPromise = new Promise(function(resolve) {
				playerArray[index].id.on(&#39;turn&#39;, (turn) =&gt; {
		    	resolve(turn);
				})
		  });
		  console.log(myPromise);
		}

		 this._playerArray[index].action = await getAction(index, pArray);
		 console.log(this._playerArray);
		 console.log(&#39;bettingPhase finish&#39;);

	}

</details>


# 答案1
**得分**: 0

你忘记在你的`getAction`函数中返回你的Promise。

像这样:

```javascript
function getAction(index, playerArray) {
    var action = null;
    let myPromise = new Promise(function(resolve) {
        playerArray[index].id.on('turn', (turn) => {
            resolve(turn);
        })
    });
    return myPromise;
}
英文:

You forgot to return your promise in your getAction function.

Like this :

function getAction(index, playerArray) {
    var action = null;
    let myPromise = new Promise(function(resolve) {
        playerArray[index].id.on(&#39;turn&#39;, (turn) =&gt; {
            resolve(turn);
        })
    });
    return myPromise;
} 

huangapple
  • 本文由 发表于 2023年1月5日 09:36:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75013042.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定