创建非阻塞函数 - Node.js

时间:2015-12-10 23:31:16

标签: javascript node.js

想象一下,我有一个像这样的阻塞函数(程序将等待执行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.

2 个答案:

答案 0 :(得分:2)

node.js只进行非阻塞I / O(文件系统读/写,网络请求等)。 JavaScript仍然是单线程的,长时间运行的代码将阻止事件循环。

有一些方法可以推迟这些操作或在子进程中运行它们,但这有点复杂。

查看this answer

答案 1 :(得分:1)

你想使用Promise。如果传递一个应在操作完成后调用的函数,则可以模拟和理解它。通过调用setImmediate(),您可以推迟执行该函数内的代码。

相关问题