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 executepostMessage
onWorker
: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 executepostMessage
onWorker
: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?
2 Answers
Reset to default 5About 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条)