If you have two lines of code (C1 followed by C2), then C2 cannot begin running until C1 has finished executing.
If you have two lines of code (L1 followed by L2), where L1 schedules some task to be run in the future, but L2 runs before that task completes.
The output is Hello! Hello again! (Wait for two seconds) Goodbye!
Because the call back function will be put in the event loop, wait until all the tasks are finished in the thread, and then excute the tasks in the event loop.
setTimeout in the example above,
$.get does not pause the execution of the code, it just schedules some code to run once the server responds. That means the return data; line will run before data = response, so the code above will always print “The data is: undefined”.
Asynchronous code needs to be structured in a different way than synchronous code, and the most basic way to do that is with callback functions.
That is, instead of
we will pass in a callback function to
Of course, how does
getData know that we’re passing in a function? How does it get called, and how is the
data parameter populated? Right now, none of this is happening; we need to change the
getData function as well, so it will know that a callback function is its parameter.
You’ll notice that we were already passing in a callback function to
$.get before, perhaps without realizing what it was. We also passed in a callback to the
setTimeout(callback, delay) function in the first example.
$.get already accepts a callback, we don’t need to manually create another one in
getData, we can just directly pass in the callback that we were given:
setInterval, or AJAX requests.