Home  >  Article  >  Web Front-end  >  Node.js event loop

Node.js event loop

黄舟
黄舟Original
2017-01-17 15:38:271155browse

Event loop

Node.js single thread is similar to entering a while(true) event loop until no event observer exits.

Each asynchronous event generates an event observer , if an event occurs, the callback function is called.

Node.js event loop

Case: loop.js

[code]// 引入 events 模块
var events = require('events');
// 创建 eventEmitter 对象
var eventEmitter = new events.EventEmitter();
// 创建事件处理程序
var connectHandler = function () {
    console.log('连接成功');

    // 触发 data_received 事件
    eventEmitter.emit('data_received');
}
// 绑定 connectHandler 事件处理程序
eventEmitter.on('connection', connectHandler);

// 使用匿名函数绑定 data_received处理事件处理函数
eventEmitter.on('data_received', function () {
    console.log('数据接收成功');
})
// 触发 connection 事件
eventEmitter.emit('connection');
console.log('执行完毕');

Result:

Node.js event loop

The above is the content of the Node.js event loop. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn