英文:
Wait for .on() to be fulfilled, not pending?
问题
我的期望输出是让 this._playerArray[index].action
实际上包含玩家的动作。我希望编写 "await getAction()" 会停止我的代码运行。问题是,Promise 处于挂起状态,代码不等待它被履行就继续执行。
有没有办法编写代码,让我的代码等待 Promise 被履行,即等待从客户端发出的事件?请注意,代码运行得非常快,玩家没有机会输入任何内容。
下面的代码输出 "promise {
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('turn', (turn) => {
resolve(turn);
})
});
console.log(myPromise);
}
this._playerArray[index].action = await getAction(index, pArray);
console.log(this._playerArray);
console.log('bettingPhase finish');
}
</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('turn', (turn) => {
resolve(turn);
})
});
return myPromise;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论