Reputation: 11
I have been working on our big-scale project trying to integrate Web Workers using Comlink - https://www.npmjs.com/package/comlink.
So far, I was able to make my Web Worker through comlink and transfer some data such as objects and functions (functions with the help of proxy
). However, some functions fail to be proxied because they may contain an argument which is a function that returns a function (Higher order functions). When this happens I receive an error:
comlink.mjs:238 Uncaught (in promise) DOMException: Failed to execute 'postMessage' on 'MessagePort': function (url, _ref) { var qs = _ref.qs, optionsWithoutQs = _objectWithoutProperties(_ref, ["qs"]);...<omitted>... } could not be cloned.
Follows the code
function queryParser(otherFn) {
return (url, { qs, ...optionsWithoutQs }) => {
const qsPart = queryString.stringify(qs) || '';
const urlWithQS = `${url}${qsPart ? '?' : ''}${qsPart}`;
return requestFunction(urlWithQS, optionsWithoutQs);
};
}
function nonTransferableFn() {
return {
...
myOtherFunction: queryParser()
}
}
const webWorkerProxy = wrap(new Worker(new URL('./web-worker.js', import.meta.url)));
const webWorkerInstance = await new webWorkerProxy();
webWorkerInstance.initialize(nonTransferableFn: proxy(nonTransferableFn));
I believe this happens because the of the higher order function here. How to solve this through the comlink? Is there any solution for this?
It is not possible at this stage to change the syntax of the function as the project is huge, and we use this pattern in too many places.
Any help is greatly appreciated!
Upvotes: 1
Views: 1042
Reputation: 33755
Passing a function across the web worker boundary in either direction requires a proxy. You are correctly proxying nonTransferableFn
to be passed to the web worker, but you are not proxying requestFunction
which is being passed back.
return proxy(requestFunction(urlWithQS, optionsWithoutQs))
Upvotes: 0