JavaScript: 是否可以在 web worker 中使用生成器函数?

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

我想将一些数据从 web worker 流式传输到父进程。我尝试使用:

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);

但这会抛出 Uncaught DOMException: Failed to execute 'postMessage' on 'DedicatedWorkerGlobalScope': [object Generator] could not be cloned.。将 "yield" 替换为 "return" 并从函数声明中删除星号会使错误消失(但它当然会阻止将结果流式传输到父进程)。

有谁知道如何在网络工作者中使用生成器?其他人可以就此问题提供的任何指示将不胜感激!

sef.process() returns 一个迭代器调用生成器,它有一个 next 函数。下一个函数不能发送回主代理并在那里调用,那会破坏代理的分离,所以根本不能这样做。您必须在 worker 中使用迭代器,并且只将结果与消息一起发送。

  // 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;
  };