Callbacks are functions passed to another function to be executed after a task completes, while events are occurrences that can trigger multiple listeners, allowing for a one-to-many relationship.
Key takeaways:
EventEmitter
and callbacks both manage asynchronous operations, but callbacks handle single events, whileEventEmitter
manages multiple events.Callbacks require manual error handling while
EventEmitter
provides built-in error events.Callbacks suit simpler tasks while
EventEmitter
is better for complex, event-driven architectures.Callbacks use direct function calls, while
EventEmitter
usesemit
andon
methods for structured event management.
Node.js is asynchronous by default. This means executing the next code statement starts even if the previous statement has not finished executing. Because of this behavior, we use callback functions to make asynchronous calls. Callback functions are sent as arguments to other functions and are only called when the method that contains the callback stops execution.
Callbacks are just functions and can be written as standard JavaScript or arrow functions.
function my_higher_order_function(my_argument1,my_argument2, my_callback){//your logicmy_callback()}my_higher_order_function(my_argument1,my_argument2, () => console.log("hey, I am a callback function"))
This file shows the implementation of a callback using a function declaration. We initialize a higher-order function—a method that receives other functions, like a callback, as an argument. my_callback
is being passed as an argument and will be called inside it. We declare a callback as an arrow function. With this callback, we are logging hey, I am a callback function
string to the console.
EventEmitter
classThe EventEmitter
class from the events
module is used by many Node.js objects. With the EventEmitter
class, we can create, listen to, and handle events.
The files shown below demonstrate the syntax of the event emitter object.
const EventEmitter = require("events");const my_event_emitter = new EventEmitter();my_event_emitter.emit("new-event");my_event_emitter.on("new-event", () =>{console.log("Callback function called after new-event's execution");});
We import the events
module before creating the my_event_emitter
object and then instantiate my_event_emitter
object from the EventEmitter
class. The event emitter object, my_event_emitter
, allows us to use various functions. For example, we can trigger an event using the emit
method to trigger events. emit
will call all event listeners registered against the event synchronously. new-event
is the name of the event. The on
method binds a function or an object to an event—also called an event listener—which handles what will happen after the event has occurred. With this, we can add a callback function as an event listener. This method can add multiple listeners to a single event without checking if the same listener has been added previously.
EventEmitter
Both callbacks and event emitter objects handle events, but they are still different in several ways, summarized in the table below.
Callback | EventEmitter |
Handles events that are asynchronous | Triggers and handles custom events |
Usually handle a single event | Usually handle multiple events |
Callbacks are passed as arguments to other functions | EventEmitters trigger events and add event listeners for them |
Error handling has to be implemented manually | Error handling is done through error events |
Handles simple asynchronous operations | Handles more complex event-driven operations |
EventEmitter
Run the application given below and explore the differences between the two methods.
//acquire event emitter classconst EventEmitter = require("events");//function to log messages on the consolefunction log_my_message(my_message){console.log(my_message)}//callback function for setTimeoutfunction emit_event(event_emitter){event_emitter.emit('educatives_mega_event', 'In my event emitter function, my execution completes after 1 second\n\n ')}//event emitters function, which triggers educatives_mega_eventconst my_event_emitter_function= ()=> {const my_event_emitter= new EventEmitter()setTimeout(() => {emit_event(my_event_emitter)}, 1000)return my_event_emitter}//function passed as a callbackconst fun1 = (err, my_message) => log_my_message(my_message)//function executed before callback starts executionconst educatives_call_back_function = (my_callback_argument) => {console.log("After my execeution completes, a callback will begin its execution after 1 second\n\n")setTimeout(() => my_callback_argument("error message, rendering gone wrong", 'Callback function reporting after 1 seconds, Hello Educative users\n\n'), 1000)}//calling event emitter object's on method to register an event listenermy_event_emitter_function().on('educatives_mega_event', my_message => log_my_message(my_message))educatives_call_back_function(fun1)
Lines 1–7: We acquire the EventEmitter
class and define the log_message
function to log other function messages to the console.
Lines 10–12: We define the emit_event
function as a callback to the setTimeout
function. It will emit the educatives_mega_event
event and log a string to the screen.
Lines 15–19: The my_event_emitter
function will create the my_event_emitter
object and call the setTimeout
function, passing emit_event
as its callback. This means that when 1 second commences, the callback function will be called.
Line 22–28: fun1
will call the log_message
function. We’ll also call the educatives_call_back_function
. The name can be a bit deceiving, but it is just a wrapper for the setTimeout
function and is executed before the actual callback function. The callback function will be executed after it.
Lines 30–32: Lastly, we call the on
method of the event emitter object, which will add the arrow function my_message => log_my_message(my_message)
as an event listener for the educatives_mega_event
event.
In conclusion, event emitters trigger and handle custom events. They can have multiple listeners attached to the same event. In contrast, callbacks follow a one-to-one relationship—each event has a single associated callback. Also, callbacks deal with simpler operations, while event emitters handle more complex ones. Moreover, they are syntactically different, with callbacks requiring more manual labor on the developer’s part than event emitters because the programmer has to cater to both normal and erroneous outcomes.
Haven’t found what you were looking for? Contact Us
Free Resources