Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...