事件和函数的区别?
我是 Node 新手,我很难理解事件和函数之间的主要区别.两者都需要被触发,那么如果我们必须触发它,为什么我们还需要一个事件呢?
I am new to Node, and I am struggling to understand the main difference between Events and Functions. Both need to be triggered, so why do we need an Event at all if we have to trigger it anyway?
这与触发函数有何不同?
How is it different than having a Function triggered?
示例代码:
var events = require('events');
var eventEmitter = new events.EventEmitter();
eventEmitter.on('event1', function () {
console.log('Event 1 executed.');
eventEmitter.emit('event2');
});
eventEmitter.on('event2', function() {
console.log('Event 2 executed.');
});
eventEmitter.emit('event1');
console.log('Program Ended.');
我们可以通过函数来达到同样的效果,对吧?
We can achieve the same result by functions, right?
我确信这在 Node 中非常重要(否则它不会存在,哈哈),但我很难理解它.
I am sure this has some serious importance in Node (otherwise it would not exist, lol), but I am struggling to understand it.
帮助表示赞赏!:)
推荐答案
事件处理异步操作.从可以互换的意义上说,它们与函数并没有真正的关系.
Events deal with asynchronous operations. They aren't really related to functions in the sense that they are interchangeable.
eventEmitter.on
本身就是一个函数,它接受两个参数作为事件名称,然后是一个函数(回调)在事件发生时执行.
eventEmitter.on
is itself a function, it takes two arguments the event name, then a function (callback) to be executed when the event happens.
eventEmitter.on(evt, callback)
没有办法知道事件将在何时发出,因此您提供了一个回调,以便在事件发生时执行.
There is no way to tell WHEN the event will be emitted, so you provide a callback to be executed when the event occurs.
在您的示例中,您正在控制触发事件的时间,这与现实世界的使用不同,在现实世界中,您可能有一个服务器侦听可以随时连接的连接.
In your examples, you are controlling when the events are triggered, which is different than real world use where you may have a server listening for connections that could connect at anytime.
server.listen('9000', function(){
console.log('Server started');
});
server.on('connection', function(client){
console.log('New client connected');
doSomethingWithClient(client);
});
//series of synchronous events
function doSomethingWithClient(client){
//something with client
}
对于 server.listen
,服务器不会立即启动,一旦准备好就会调用回调
For server.listen
the server doesn't start immediately, once its ready the callback is called
server.on('connection')
监听客户端连接,它们可以随时到来.然后在发生连接时触发该事件,从而运行回调.
server.on('connection')
listens for client connections, they can come at any time. The event is then triggered when a connection occurs, causing the callback to be run.
然后是doSomethingWithClient
,这只是一个函数,当客户端连接发生时,需要执行一组同步操作.
Then there is doSomethingWithClient
this is just a function with a set of synchronous operations to be done when a client connection occurs.
相关文章