Is it safe to listen to an event AFTER registering it?

I'm new to NodeJS, and I'm learning how it works with streams. Reading a book I found this sample code:

var CountStream = require('./countstream');
var countStream = new CountStream('book');
var http = require('http');

http.get('http://www.manning.com', function(res) {
    res.pipe(countStream);
});

countStream.on('total', function(count) {
    console.log();
});

In this code snippet we're calling http.get method and then waiting for the callback (Part 1).

On the next line we're listening for total event (Part 2).

Question: What if a delay happens between Part 1 and Part 2, so the Part 1's callback executes first (before Part 2 starts listening to to total event. Is it true that the first chunk(s) of data will be lost?

Answers:

Answer

No, because you're not "waiting" for the callback. The callback is asynchronous, and will be executed after the http.get function has returned. Part 2 will be executed before the callback functin (Part 1) is invoked.

It is totally safe to construct an asynchronous event emitter and register event handlers only after the construction (as long as it happens synchronously), as the events will only be emitted in the next turn of the event loop.

See also Hidden threads in Javascript/Node that never execute user code: is it possible, and if so could it lead to an arcane possibility for a race condition?.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.