[英]Creating non blocking function - Node.js
Imagine that I have a blocking function like this (the program will wait for the execution of random_operations
: 想象一下,我有一个这样的阻塞函数(程序将等待执行
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? 这样使用
random_operations
意味着node.js将不会阻塞? I am trying to understand how can I non-block the node.js. 我试图了解如何不阻塞node.js。
node.js only does non-blocking I/O (filesystem reads/writes, network requests etc). node.js仅执行非阻塞I / O(文件系统读取/写入,网络请求等)。 JavaScript is still single threaded and long-running code will block the event loop.
JavaScript仍然是单线程的,并且长时间运行的代码将阻止事件循环。
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 看看这个答案
You want to use Promise. 您要使用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. 通过调用
setImmediate()
您可以推迟该函数内部代码的执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.