最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript passing a function object to a web worker - ERROR DataCloneError could not be cloned - Stack Overflow

programmeradmin1浏览0评论

I need to use a web worker to open a separate thread an do some heavy CPU task.

I would need to task the web worker with a function call and arguments and then get the return, so I went for:

funcs.js

export default function add(args) {
  return args[0] + args[1];
}

main.js

import add from './funcs.js';
// [...]
this.worker.postMessage({func: add, args: [7, 3]});

then runtime error:

DataCloneError: Failed to execute postMessage on Worker: function add(args) { return args[0] + args[1]; } could not be cloned.

It seems the worker.postMessage method only allow string to be passed, any idea how I can work this around simply and elegantly?

I need to use a web worker to open a separate thread an do some heavy CPU task.

I would need to task the web worker with a function call and arguments and then get the return, so I went for:

funcs.js

export default function add(args) {
  return args[0] + args[1];
}

main.js

import add from './funcs.js';
// [...]
this.worker.postMessage({func: add, args: [7, 3]});

then runtime error:

DataCloneError: Failed to execute postMessage on Worker: function add(args) { return args[0] + args[1]; } could not be cloned.

It seems the worker.postMessage method only allow string to be passed, any idea how I can work this around simply and elegantly?

Share Improve this question edited Oct 29, 2019 at 16:21 Alessio Cantarella 5,2113 gold badges29 silver badges36 bronze badges asked Oct 29, 2019 at 16:08 uzer44713543uzer44713543 211 silver badge4 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

About postMessage

postMessage documentation give a clear definition about what can or cannot be send to a worker:

postMessage accept only value or JavaScript object handled by the structured clone algorithm, which includes cyclical references.

Looking at the structured clone algorithm, it accept :

All primitive types (However, not symbols), Boolean object, String object, Date, RegExp (The lastIndex field is not preserved.), Blob, File, FileList, ArrayBuffer, ArrayBufferView (This basically means all typed arrays like Int32Array etc.), ImageBitmap, ImageData, Array, Object (This just includes plain objects (e.g. from object literals)), Map, Set

But unfortunately :

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

So function is definitely not an option. A simple solution would be to import add directly in your worker.js file, and replace func by a string.

Javascript

this.worker.postMessage( {func: 'ADD', args:[7, 3]} );

worker.js

import add from './funcs.js';

onmessage = function(event) {
    const action = event.data;
    switch (action.func) {
        case 'ADD': {
            postMessage({
                result: add(action.args)
            });
        }
        break;
        ....

Well there I a way to call the function using eval, but you should be very careful when you use it.

For example:

main.js

import add from './funcs.js';
// [...]
this.worker.postMessage({func: `${add}`, args: [7, 3]});

worker.js

onmessage = function(event) {
    eval(event.func)(...event.args);
}

The important thing - you should avoid using anything out of function scope in the function.

发布评论

评论列表(0)

  1. 暂无评论