Trying to find an efficient method for utilizing web workers to handle api calls, my current approach involves the following on the client side:
- worker-client.js
export const workerFetch = (method = "get", url = "/", data = {}) =>
new Promise((resolve, reject) => {
const listener = `worker_fetch_${url}_${new Date()}`;
window.lootWorker.postMessage({
cmd: "worker_fetch",
payload: { method, url, data, listener }
});
window.addEventListener(
"message",
({ data }) => {
if (data.cmd === listener) {
if (data.success) resolve(data.data);
else reject(data.data);
}
},
false
);
});
The client can call this function with specific parameters. On the other side, inside the web worker itself:
- worker-thread.js
const workerFetch = ({ method = "get", url = "", data = {}, listener = "" }) => {
fetch({ method, url, data })
.then(({ data }) => {
self.postMessage({ cmd: `worker_fetch_${listener}`, success: true, data });
})
.catch(error => {
self.postMessage({ cmd: `worker_fetch_${listener}`, success: false, data: error });
});
};
self.addEventListener(
"message",
({ data }) => {
switch (data.cmd) {
case "worker_fetch":
workerFetch(data.payload);
break;
default:
return null;
}
},
false
);
In theory, this setup functions as intended. However, I am wary of the event listeners accumulating in the client side. Thus, I wonder if there is a more optimized approach to achieve this functionality with a focus on performance? After all, the goal is to lighten the main thread load.