想象一下,我有一个这样的阻塞函数(程序将等待执行random_operations
:
var result = random_operations(arg1,arg2);
但是现在我做了这个:
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);
这样使用random_operations
就意味着node.js不会被阻止吗?我试图了解如何不阻塞node.js。
node.js仅执行非阻塞I / O(文件系统读取/写入,网络请求等)。JavaScript仍然是单线程的,并且长时间运行的代码将阻止事件循环。
有许多方法可以推迟此类操作或在子进程中运行它们,但这要复杂一些。
看看这个答案
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句