Reputation: 529
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.
Upvotes: 0
Views: 144
Reputation: 873
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.
Upvotes: 1
Reputation: 179
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
Upvotes: 2