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.

2
  • Just try setImmediate(). It is magic function you want. Commented Dec 10, 2015 at 23:54
  • 1
    Well, it is and it isn't. It will just postpone the execution. If your code takes 5s to run it WILL block the event loop for 5s. No matter what. Commented Dec 11, 2015 at 9:35

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

My objective is to non-block the nodej.js. Promises will block to. @avesus
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.
The solution I offer is to call lenghty code with setImmediate. It allows it to mix in time with another code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.