How can you use a callback to guarantee sequential execution?

后端 未结 3 1621
夕颜
夕颜 2021-01-28 08:17

I am trying to wrap my head around callbacks and I do not understand how callbacks guarantee that a statement will execute after(in terms of time)

3条回答
  •  自闭症患者
    2021-01-28 09:06

    Callbacks is a way of invoking a function that is passed as a parameter to invoker function(in your example foo). Callbacks guarantee that a function will be invoked if no error occurs before it's call inside the function. Callbacks aren't asynchronous either but the way it executes later inside the function after some line of code makes everyone think it as asynchonous at first.

    And as you've added setTimeout function on the above example, setTimeout is an asynchronous callback envoker function that calls it's callback(in your code () => console.log("Do something with unknown time")) asynchronously after a certain defined time(2000). So, setTimeout wont stop the execution for 2 seconds as you've expected, instead it let's the further line of codes execute without worrying about what will happen inside it's callback. So, the callback() will trigger at that instant when foo(callback); is triggered.

    You can find more info about callback in here.

提交回复
热议问题