是否可以将回调传递给网络工作者?

Is it possible to pass a callback to a webworker?

我有一个渲染器,我想将回调传递给它。我知道 worker.postMessage 方法现在支持 Javascript 对象,但是当我尝试使用该对象传递函数时,我收到一条错误消息,告诉我它是 "couldn't clone" 对象。

我还在对象上尝试了 JSON.stringify(),了解到函数不会被字符串化,因为 JSON 不支持函数作用域。

有没有办法将回调传递给 Web Worker?如果没有,您建议如何解决该限制?

我的问题是我在启动动画的同时向工作人员发送了一条消息以启动渲染。所以我需要等到两者都完成后再执行 "callback"

Is there a way to pass a callback to a Web Worker?

来自MDN

The postMessage() method of the Worker interface sends a message to the worker's inner scope. This accepts a single parameter, which is the data to send to the worker. The data may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references.

also

Things that don't work with structured clones

  • Error and Function objects cannot be duplicated by the structured clone algorithm; attempting to do so will throw a DATA_CLONE_ERR exception.

所以没有。你不能传递函数 about.

My issue is that I send the worker a message to start the rendering at the same time I start an animation. So I need to wait until BOTH are finished before executing the "callback"

生成唯一 ID(例如,时间戳与随机数连接)。存储它。关联任何你喜欢的数据(包括你想用作回调的函数)。将它传递给动画处理程序和网络工作者的末端。

工作完成后发回该 ID。侦听其中具有该 ID 的事件,并在您的数据结构中查找它。