繁体   English   中英

在 function 内:防止后面的 function 执行,直到前面的功能(使用用户输入)完成

[英]Within a function: prevent a later function from executing until earlier functions (with user input) are completed

我正在创建一个练习 JS 的游戏,并希望能够限制 function 的执行,直到 function 的早期部分完成。 我正在创建一个模态,其中有 2 个预建功能馈送到两个按钮,然后在按下其中一个按钮并且按钮的 function 完成后,然后后面的 function 可以 Z34D1F91FB2E514B856BABZFA。

以下是一些通用示例:

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 Z,因此将functionZ Z 移动到 X 和 Y 作为其执行的一部分是不切实际的。

我已经搞砸了承诺,但似乎仍然无法让它完全按照我的需要工作,我认为这是因为 promise 仍然不在乎functionXfunctionY是否完成,它只关心它们已经被执行.

可以在每个点击处理程序中调用functionZ

buttonX.on("click",function() {x(); functionZ()})
buttonY.on("click",function() {y(); functionZ()})

或者,如果您希望此行为仅可用一次,请将点击处理程序包装在 promise 中,并在解决后调用functionZ

var promise = new Promise(function (resolve) {
  buttonX.on("click",function() {x(); resolve()})
  buttonY.on("click",function() {y(); resolve()})
}

promise.then(functionZ)

这是假设xy是同步的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM