编程语言
首页 > 编程语言> > javascript – 是否可以将回调传递给网络工作者?

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

作者:互联网

我有一个渲染工作者,我想通过回调.我知道worker.postMessage方法现在支持Javascript对象,但是当我尝试传递带有对象的函数时,我收到一个错误,告诉我它“无法克隆”该对象.

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

有没有办法将回调传递给Web Worker?如果没有,你会如何建议解决这个限制?

我的问题是我在发送动画的同时向工作人员发送消息以启动渲染.所以我需要等到BOTH完成才能执行“回调”

解决方法:

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.

所以不,你不能传递函数.

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(例如,与随机数连接的时间戳).存放它.关联您喜欢的任何数据(包括您想要用作回调的函数).将它传递给动画处理程序和Web worker的末尾.

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

标签:javascript,web-worker
来源: https://codeday.me/bug/20190823/1700243.html