0

Imagine that I have a blocking function like this (the program will wait for the execution of random_operations:

var result = random_operations(arg1,arg2);

But now I make this:

function Op() {
  events.EventEmitter.call(this);

  this.get= function(arg1, arg2)
  {
  this.arg1 = arg1;
  this.arg2 = arg2;
  this.result = random_operations(this.arg1,this.arg2);
  this.emit('done', this.result);
  }
}

Op.prototype.__proto__ = events.EventEmitter.prototype;
var do_job = new Op();

do_job.on('done', function(resulted) {
    console.log('done '+ resulted);
  });

dojob.get(_arg1, _arg2);

Using random_operations like this means that node.js will not block? I am trying to understand how can I non-block the node.js.

carduh
  • 529
  • 1
  • 4
  • 13

2 Answers2

2

node.js only does non-blocking I/O (filesystem reads/writes, network requests etc). JavaScript is still single threaded and long-running code will block the event loop.

There are ways to defer such operations or run them in a child process, but that's a little more complicated.

Take a look at this answer

Community
  • 1
  • 1
klaemo
  • 169
  • 6
1

You want to use Promise. You could emulate and understand it if pass a function which should be called after the operation completes. With call to setImmediate() you could postpone execution of the code inside that function.

Brian Cannard
  • 852
  • 9
  • 20
  • My objective is to non-block the nodej.js. Promises will block to. @avesus – carduh Dec 10 '15 at 23:58
  • 1
    You postpone execution of current part of code with promises and setImmediate(). You could write async code in C++ for node extension. But JavaScript is always run SINGLE-THREADED. – Brian Cannard Dec 11 '15 at 00:00
  • 1
    The solution I offer is to call lenghty code with setImmediate. It allows it to mix in time with another code. – Brian Cannard Dec 11 '15 at 00:02