问题描述
我是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) ,回调)
没有办法告诉WHEN事件将被发出,所以你提供一个回调,当事件发生时执行。
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.
这篇关于NodeJS:事件和函数之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!