0

When writing a simple event:

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

The result is displayed asynchronously:

a function starts execution
function is executed
a function starts execution
function is executed
a function starts execution
function is executed
1
2
3

But in the socket event 'data' is processed synchronously, the following event does not begin to run until the end of the previous event:

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

}

Result when sending the socket nc -U /tmp/sockets/test.sock data:

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

How to handle events asynchronously?

rail-ka
  • 13
  • 1
  • 1
    On one side `console.log('function is executed');` is inside `setImmediate` and on the other side, it's after. – L. Meyer Feb 25 '17 at 09:25
  • You are not comparing fairly. the callback function passed to `setImmediate` is always executed asynchronously. Your results are in line with that. For how to process data provided by asynchronously called functions: see Q&A on SO. – trincot Feb 25 '17 at 09:47

0 Answers0