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

后端 未结 4 765
[愿得一人]
[愿得一人] 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:46

    Place the callback inside setTimeout and not outside as the callback will be executed first before the setTimeout does as javascript won't wait for setTimeout execution(as JS is synchronous by nature) and executes the next line and hence you won't get the desired output.

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

    Demo

提交回复
热议问题