简体   繁体   English

JavaScript:是否可以在 web 工作人员中使用生成器功能?

[英]JavaScript: Is it possible to use generator functions in web workers?

I would like to stream some data from a web worker to the parent process.我想 stream 一些数据从 web 工作人员到父进程。 I tried to do so using:我试图这样做使用:

var s = `
  self.onmessage = function(event) {
    postMessage(self.process(event.data))
  };
  self.process = function* (n) {
    for (var i=0; i<n; i++) yield i;
  }
`
var blob = new Blob([s], {type: 'application/javascript'});
var worker = new Worker(URL.createObjectURL(blob));

worker.onmessage = e => {console.log('got back', e.data)}
worker.postMessage(7);

But this throws Uncaught DOMException: Failed to execute 'postMessage' on 'DedicatedWorkerGlobalScope': [object Generator] could not be cloned.但这会引发Uncaught DOMException: Failed to execute 'postMessage' on 'DedicatedWorkerGlobalScope': [object Generator] could not be cloned. . . Replacing "yield" with "return" and removing the star from the function declaration makes the error go away (but it prevents one from streaming results to the parent process of course).将“yield”替换为“return”并从 function 声明中删除星号会使错误 go 消失(但它当然会阻止将结果流式传输到父进程)。

Does anyone know how one can use generators in web workers?有谁知道如何在 web 工人中使用发电机? Any pointers others can offer on this question would be greatly appreciated!其他人可以就这个问题提供的任何指示将不胜感激!

Calling the generator with sef.process() returns an iterator, that has a next function.使用sef.process()调用生成器会返回一个迭代器,它具有下一个 function。 That next function cannot be sent back to the main agent and called there, that would break the seperation of agents, so this cannot be done at all.下一个 function 不能被送回主代理并在那里调用,这会破坏代理的分离,所以这根本不能做。 You have to consume the iterator in the worker and only send the results with messages.您必须在工作人员中使用迭代器,并且只发送带有消息的结果。

  // In the worker: Consume the iterator:

  self.onmessage = function(event) {
     const it = self.process(event.data); // this contains a function, so it has to stay here
     let result;
     do { 
        postMessage(result = it.next());  // but the iteration objects can be sent, they onyl contain a number and a boolean
      } while(!result.done);         
  };

  self.process = function* (n) {
    for (var i=0; i<n; i++) yield i;
  };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM