撰写简单的活动时:
const EventEmitter = require('events');
let myEmitter = new EventEmitter();
myEmitter.on('aaa', (d) => {
let ii = 1;
console.log('a function starts execution');
setImmediate(() => {
for (let i = 1; i < 1000000000; i++) {
ii = ii * i;
}
console.log(d);
});
console.log('function is executed');
});
myEmitter.emit('aaa', 1);
myEmitter.emit('aaa', 2);
myEmitter.emit('aaa', 3);
结果以异步方式显示:
a function starts execution
function is executed
a function starts execution
function is executed
a function starts execution
function is executed
1
2
3
但是在套接字事件'data'被同步处理时,以下事件直到上一个事件结束才开始运行:
const net = require('net');
const fs = require('fs');
const UNIX_DOMAIN_PATH = '/tmp/sockets';
try{
fs.unlinkSync(UNIX_DOMAIN_PATH + '/test.sock');
} catch (err) {}
const server = net.createServer();
server.on('connection', handleConnection);
server.listen(UNIX_DOMAIN_PATH + '/test.sock');
function handleConnection(conn) {
console.log('new client connection');
let i = 0;
conn.on('data', (d) => {
i++;
console.log('i = ' + i);
setImmediate(() => {
let ii = 1;
console.log('a function starts execution');
console.log(d);
for (let i = 1; i < 1000000000; i++) {
ii = ii * i;
}
console.log('function is executed');
});
console.log('end');
});
conn.once('close', onConnClose);
conn.on('error', onConnError);
function onConnClose() {
console.log('connection closed');
}
function onConnError(err) {
console.log('Connection error: %s', err.message);
}
}
发送套接字nc -U /tmp/sockets/test.sock
数据时的结果:
new client connection
i = 1
end
a function starts execution
<Buffer 31 0a>
function is executed
i = 2
end
a function starts execution
<Buffer 31 0a>
function is executed
如何异步处理事件?