简体   繁体   English

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

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

I am creating a game to practice JS and would like to be able to restrict a function from executing until earlier parts of the function are done.我正在创建一个练习 JS 的游戏,并希望能够限制 function 的执行,直到 function 的早期部分完成。 I'm creating a modal with 2 pre-built functions fed to two buttons, and then after one of the buttons is pressed and the button's function is finished, THEN the later function can go.我正在创建一个模态,其中有 2 个预建功能馈送到两个按钮,然后在按下其中一个按钮并且按钮的 function 完成后,然后后面的 function 可以 Z34D1F91FB2E514B856BABZFA。

Here are some general examples:以下是一些通用示例:

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());

Many functions (X and Y) in the game become part of the modal, and could be followed by different kinds of functionZ s, so it's not practical to move functionZ into X and Y as part of their execution.游戏中的许多函数(X 和 Y)成为模态的一部分,并且可以跟随不同类型的functionZ Z,因此将functionZ Z 移动到 X 和 Y 作为其执行的一部分是不切实际的。

I have messed around with promises and still can't seem to get it to work exactly how I need, and I think that's because the promise still doesn't care whether functionX or functionY is done, it just cares that they've been executed.我已经搞砸了承诺,但似乎仍然无法让它完全按照我的需要工作,我认为这是因为 promise 仍然不在乎functionXfunctionY是否完成,它只关心它们已经被执行.

could call functionZ within each click handler:可以在每个点击处理程序中调用functionZ

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

or if you want this behavior to only be available once, wrap the click handlers in a promise and call functionZ after it resolves:或者,如果您希望此行为仅可用一次,请将点击处理程序包装在 promise 中,并在解决后调用functionZ

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

promise.then(functionZ)

this is assuming x and y are synchronous这是假设xy是同步的

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

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