javascript函数同步

javascript function synchronization

本文关键字:同步 函数 javascript      更新时间:2023-09-26

我有这样的东西:

<html>
<script type="text/javascript">
    //BLOCK1
    function startingFunction() {
        //do a server call, receive the response through callback functions, either successFunction or failFunction
        onSuccess : successFunction,
        onFailure : failFunction
    }
    function successFunction(result) {
        //called receiving the server response
        //configure something based on success
    }
    function failFunction(result) {
        //called receiving the server response
        //configure something based on failure
    }
</script>
<script type="text/javascript">
    // BLOCK2
    //javascript code that needs to wait for the result of the configuration made above in BLOCK1 in order to continue doing more stuff
</script>
<body>...</body>
</html>

我如何让BLOCK2中的javascript代码等待服务器做出响应并进行配置?

您可以简单地从第一个块中可以调用的两个函数中调用第二个块中的一个函数。(假设你想在失败后继续)

<script type="text/javascript">
    //BLOCK1
    function startingFunction() {
        //do a server call, receive the response through callback functions, either successFunction or failFunction
        onSuccess : successFunction,
        onFailure : failFunction
    }
    function successFunction(result) {
        //called receiving the server response
        //configure something based on success
        afterConfiguration();
    }
    function failFunction(result) {
        //called receiving the server response
        //configure something based on failure
        afterConfiguration();
    }
</script>
<script type="text/javascript">
    // BLOCK2
    //javascript code that needs to wait for the result of the configuration made above in BLOCK1 in order to continue doing more stuff
    function afterConfiguration(){
      //code that needed to wait
    }
</script>

只需将代码放在函数内的块2中,然后在successFunction结束时调用该函数。

再说一遍,我不认为把它分成两个script元素有什么意义。

您也可以使用标志并使用setInterval()定期检查:

使用标志:

<html>
<script type="text/javascript">
//BLOCK1
var block1Success = false; // <-- this is our flag
function startingFunction() {
    //do a server call, receive the response through callback functions, either successFunction or failFunction
    onSuccess : successFunction,
    onFailure : failFunction
}
function successFunction(result) {
    //called receiving the server response
    //configure something based on success
    block1Success = true; // <-- flag is set here
}
function failFunction(result) {
    //called receiving the server response
    //configure something based on failure
}
</script>
<script type="text/javascript">
// BLOCK2
//javascript code that needs to wait for the result of the configuration      made above in BLOCK1 in order to continue doing more stuff
window.setInterval(
    function(){
       if(block1Success){ 
         // code need to be executed here..
         alert("block1 success executed");
       }
    }, 100)
</script>
<body>...</body>
</html>