At first, Async is about being non-blocking: you start a task and
your program keeps running instead of waiting for it to finish.
Event-driven is about being notified when something specific happens
in the system.
The key difference is when the callback runs:
- In async, the callback executes when a long task finishes (e.g., a file is read, a database responds).
- In event-driven, the callback executes when a specific event occurs (e.g., a user clicks a button, a message arrives on a queue).
Now the question is — what happens inside the event handler? Most of the time, it needs to do some work that takes time (read a file, query a database, call an API). That's exactly where async comes in.
Async Handler Inside an Event
const EventEmitter = require('events');
const emitter = new EventEmitter();
`// The handler is async — combining both patterns
emitter.on('userSignedUp', async (user) => {
try {
await saveToDatabase(user); // async work #1
await sendWelcomeEmail(user); // async work #2
console.log('User setup complete');
} catch (err) {
console.error('Something went wrong:', err);
}
});
emitter.emit('userSignedUp', { id: 1, email: 'ali@example.com' });`
Top comments (1)
Keep this work up Aya 😎😎😎