node-webworker-threads中的异步调用?

时间:2015-05-12 03:58:42

标签: node.js web-worker

来自node-webworker-threads页面的Hello World示例工作正常,并生成Worker said: Hi ali

var Worker = require('webworker-threads').Worker;
var worker = new Worker(function(){
  postMessage("I'm working before postMessage('ali').");
  this.onmessage = function(event) {
    self.postMessage('Hi ' + event.data);
    self.close();
  };
});
worker.onmessage = function(event) {
  console.log("Worker said : " + event.data);
};
worker.postMessage('ali');

但这不起作用,我无法弄清楚原因。添加setTimeout会导致self.postMessage永远不会被调用:

var Worker = require('webworker-threads').Worker;
var worker = new Worker(function(){
  postMessage("I'm working before postMessage('ali').");
  this.onmessage = function(event) {
    setTimeout(function() {
        self.postMessage('Hi ' + event.data);
        self.close();
    },0);
  };
});
worker.onmessage = function(event) {
  console.log("Worker said : " + event.data);
};
worker.postMessage('ali');

如何使用node-webworker-threads处理异步调用?

Can someone explain the webworker-thread example?

1 个答案:

答案 0 :(得分:1)

&#34;工作人员无权访问setTimeout,setInterval等。实际上,HTML计时器规范不是v8的原生规范,需要在C ++级别重新实现。&#34; < / p>

https://github.com/audreyt/node-webworker-threads/issues/50