NodeJS Series #6: Event - Driven Programming

Event-Driven Programming

Event-Driven Programming is the term where the flow of the code is determined by events (click, load and so on). It's one of the basic milestones of today's popular programming languages, such as C#, Java and many more; I won't dwell on all of them here. In Node.js and moreover in any kind of JavaScript project, you'll be using or have used event-driven processes. Whether it's a page onload or a button click event, this is something you have done, whether you knew it or not.

Let's make an example to the classic event-driven process and how its done in NodeJS:

  1. result = getJSONfromDestination();  
  2. binddata(result);  

The operation above requires a blocking I/O process (single-threaded operation that waits for the previously working synchronous code).

Now let's have a look at how we do the asynchronous way (a non-blocking I/O process).

  1. json_finished = function(result){  
  2. binddata(result);  
  3. }  
  4.   
  5. getJSONfromDestination(jsonfinished);  
As you can see, this is a non-blocking sample, because json_finished does not work first as you can imagine.

It starts working when you call the getJSONfromDestination method and send param as the function to json_finished.

This is how asynchronous operations are completed in mainly JavaScript projects and widely used in NodeJS projects. In the case of how things work in a step-by-step manner, we send params to functions to start working whenever and however we want.

You'll be using these kinds of asynchronous operations frequently, or in other terms the “Event-Driven Programming” style, in nearly all of your JavaScript oriented applications, not to mention coding like that is a “must-have” in NodeJS applications.

In the next article, we will be experiencing a realistic problem for a detailed look. 


Similar Articles