Dan York recently wrote a blog post titled "Understanding Event-driven Programming." It's a lucid explanation of event-driven programming based on an analogy given by WebOS/Node.js developer Tim Caswell on York's Herding Code podcast.
Caswell and York use a doctor's office and fast food line as a metaphor for a computing environment. If the fast food joint followed a traditional thread-based model, you'd order your food and wait in line until you received it. The person behind you wouldn't be able to order until your order was done. In an event-driven model, you order your food and then get out of line to wait. Everyone else is then free to order.
Node.js is event-driven, but most Web servers are thread-based. York explains how Node.js works:
- You use your web browser to make a request for "/about.html" on a Node.js web server.
- The Node server accepts your request and calls a function to retrieve that file from disk.
- While the Node server is waiting for the file to be retrieved, it services the next web request.
- When the file is retrieved, there is a callback function that is inserted in the Node servers queue.
- The Node server executes that function which in this case would render the "/about.html" page and send it back to your web browser.
Considering that it only takes microseconds to serve up the page, what's the big deal? York writes: "microseconds matter! Particularly when you are talking about highly-scalable web servers!"
Please do check out his full explanation.
What do you think of the metaphors?