我尝试做的是等待,直到正确的键被按下,让它继续
到目前为止我做的代码是这样的:
class exampleClass {
async waitForKeyPress() {
return new Promise((resolve) => {
const listener = (e) => {
document.body.removeEventListener("keydown", listener);
if(e.key == "z") {resolve(); alert("e");}
else {
this.waitForKeyPress();
}
}
document.body.addEventListener("keydown", listener);
});
}
async doStuff() {
await this.waitForKeyPress();
console.log("correct key pressed");
//do stuff
}
}
let exampleObject = new exampleClass();
exampleObject.doStuff();
这对我不起作用,因为如果我按下不同的键,它不会检测到z键因某种原因被按下。
async function waitForKeyPress() {
return new Promise((resolve) => {
const listener = (e) => {
document.body.removeEventListener("keydown", listener);
if(e.key == "z") resolve();
else {
this.waitForKeyPress();
}
}
document.body.addEventListener("keydown", listener);
});
}
async function doStuff() {
await this.waitForKeyPress();
console.log("correct key pressed");
//do stuff
}
doStuff();
唯一的区别是它不在课堂上。不过,我希望它是在一个类
1条答案
按热度按时间pftdvrlh1#
仅在按下
z
时删除侦听器,而不是过早删除它。没有承诺