我正在创建一个游戏来练习JS,并希望能够限制函数的执行,直到函数的早期部分完成。我正在创建一个模态与2预构建函数馈送到两个按钮,然后在其中一个按钮被按下和按钮的功能完成后,然后后面的功能可以去。
下面是一些一般的例子:
functionX() {/*manipulate the DOM based on user input*/}
functionY() {/*manipulate the DOM based on user input*/}
functionZ() {/*changes DOM based on results of functionX or functionY*/}
functionChoice(x,y){
//create a modal with 2 buttons, one for function x and function y
//buttons have functionX or functionY bound to them
buttonX.on("click",function() {x()})
buttonY.on("click",function() {y()})
function Z();// this is the function I want to restrict until the user has clicked on, and finished, either x() or y()
}
functionChoice(functionX(), functionY());
游戏中的许多功能(X和Y)成为模态的一部分,并且可以由不同类型的functionZ
跟随,因此将functionZ
作为其执行的一部分移动到X和Y中是不现实的。
我把承诺弄得一团糟,但似乎仍然不能让它按照我需要的方式工作,我想这是因为承诺仍然不关心functionX
或functionY
是否完成,它只关心它们是否被执行。
可以在每个点击处理程序中调用functionZ
:
buttonX.on("click",function() {x(); functionZ()})
buttonY.on("click",function() {y(); functionZ()})
或者如果您希望此行为只可用一次,请将单击处理程序包装在承诺中,并在其解析后调用functionZ
:
var promise = new Promise(function (resolve) {
buttonX.on("click",function() {x(); resolve()})
buttonY.on("click",function() {y(); resolve()})
}
promise.then(functionZ)
这是假设x
和y
是同步的