How to add a callback to a function in javascript

后端 未结 4 701
既然无缘
既然无缘 2020-12-14 17:52

I have two javascript functions

function one () {
   do something long... like writing jpgfile on disk
}

function two () {
   do something fast... like show         


        
4条回答
  •  无人及你
    2020-12-14 18:07

    You only need to use a callback if you are doing something asynchronous, otherwise it doesn't matter how long something takes, the next function won't run until the first has finished.

    A callback is just passing a function as an argument, and then calling it when done.

    function one (callback) {
       do something long... like writing jpgfile on disk
       callback();
    }
    
    function two () {
       do something fast... like show the file
    }
    
    one(two);
    

    Obviously, if you are doing something asynchronous, then you need something that will tell you when it is finished (such as an event firing).

提交回复
热议问题