A. The listener callback is called immediately, not on event emit.
B. The event name 'data' is invalid for once listeners.
C. The emitter.emit call is missing a callback function.
D. The once method does not exist on EventEmitter.
Solution
Step 1: Check how the callback is passed
The code passes console.log('Data event') which calls console.log immediately and passes its return (undefined) as listener.
Step 2: Understand correct callback usage
The callback should be a function, e.g., () => console.log('Data event'), to run only on event emit.
Final Answer:
The listener callback is called immediately, not on event emit. -> Option A
Quick Check:
Pass function, not function call, as listener [OK]
Hint: Pass function, not function call, as listener [OK]
Common Mistakes:
Calling function instead of passing it
Assuming event name invalid
Thinking once method is missing
5. You want to log a message only the first time a user connects to your server using an EventEmitter server. Which code snippet correctly achieves this and prevents multiple logs if the user reconnects?
hard
A. server.on('connect', () => console.log('User connected'));
B. server.on('connect', console.log('User connected'));
C. server.once('connect', console.log('User connected'));
D. server.once('connect', () => console.log('User connected'));
Solution
Step 1: Identify the requirement for single execution
Logging only once means the listener should run once and then remove itself.
Step 2: Choose the correct method and callback syntax
server.once('connect', () => console.log('User connected')) uses the once method with a function callback, ensuring single log on first connect.
Final Answer:
server.once('connect', () => console.log('User connected')); -> Option D
Quick Check:
Use once with function callback for single event handling [OK]
Hint: Use once with function callback to run once [OK]