How do I set a specific order of execution when asynchronous calls are involved?

后端 未结 4 764
[愿得一人]
[愿得一人] 2021-01-07 08:13

I am new(2 days!!) to the world of JavaScript and my only prior coding experience is in Java where execution of statements takes place sequentially. I understand that or at

4条回答
  •  臣服心动
    2021-01-07 08:28

    I have modified your code as below to get the desired output.

    console.log("Beginning");
    function Test(callback){
    
        console.log("Something that takes a lot of time");
        setTimeout(callback,5000);
     }
    
    function tstCallBack(){
       console.log("Should come last");
    }
    Test(tstCallBack);
    

    setTimeout takes a callback function that will be executed after the specified time interval

    The use of setTimeout is the asynchronous part. When the above code is executed,first the "Begining" console statement is printed and then the Test function is called passing in a function that needs to be executed asynchronously after 500ms .

提交回复
热议问题