puki puki - 6 months ago 23
Javascript Question

javascript function synchronization

I have something like this :

<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>


How can i make the javascript code in BLOCK2 to wait until the server has responded something and the configuration has been made?

Answer

You can simply call a function in your second block from both functions that could be called in the first block. (assuming you want to continue after a failure)

<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>