它是安全的收听事件发生后注册了吗? [英] Is it safe to listen to an event AFTER registering it?

查看:101
本文介绍了它是安全的收听事件发生后注册了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的NodeJS,我正在学习如何与流工作。
读一本书,我发现这个样本code:

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();
});

在我们调用 http.get 方法,然后等待回调此code段(第1部分)。

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

在我们聆听事件下一行(第2部分)。

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

问:如果延迟发生的第1部分和第2部分之间,因此,第1部分的回调首先执行(之前的第2开始聆听到事件。这是真的,第一个数据块(S)将丢失?

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?

推荐答案

没有,因为你的不是等待回调。回调的同步 http.get 函数返回之后将被执行。第2部分将回调载体作用之前执行(第1部分)被调用。

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.

另请参阅隐藏线程在Javascript /节点未执行用户code:这是可能的,如果是的话可能会导致它为竞争条件的可能性神秘?

这篇关于它是安全的收听事件发生后注册了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆