Callbacks and the Event Loop
def and removed all
var keywords, you would be reading Ruby (true story: yesterday I was debugging an issue with a React module and put in a
binding.pry instead of
debugger :facepalm: Old habits die hard).
The Event Loop
image credit: Mario Casciaro and Luciano Mammino from Node.js Design Patterns. Colour notations are mine.
- An I/O request is sent to the event demultiplexer.
- The event demultiplexer queues the I/O instructions along with the context and a callback function that contains the instructions for what do to with the result once it is received.
- When the I/O order is filled, the event demultiplexer pops an event on to the event queue, with the filled I/O request, and the callback handler.
- The event loop pulls the event off of the event queue and applies the result to the callback function.
- The event loop either sends the result of the callback operation to the application, or generates more I/O work for the event demultiplexer.
When I check my email in the morning, I go through a similar process:
- My inbox is the event demultiplexer, where requests for resources are made.
- I (as the event loop) process emails from in the queue from oldest to newest, and I only process one at at time.
- For each message I read the context and perform one of two actions (callback):
- Process the message and return to the queue to pick up another message.
- Add a new action to my todo list event queue along with the a reminder to attach the result of the new action to the email when I respond (callback).
return statement, which returns control back to the caller.
1 2 3 4 5 6
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
createEmailAddress is called. When execution reaches the setTimeout function, and the 2000ms have elapsed, the callback passed to setTimeout is placed in the event queue, awaiting its turn for execution. The thread is release and does not have to wait for the setTimeout period to elapse before continuing execution — it continues with the second console statement (‘after the async’). When the setTimeout callback is finally processed, the
lastName variables are still accessible because they exist in the function closure.
- Closures allow you to access the environment on which a function was created, no matter when the callback is invoked.
- Functions are first class data types, meaning they can be assigned to variables, passed as parameters, and stored in data structures.
More on the event loop and event-emitter observer pattern to come!