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

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

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745183577a4615531.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信