What is the reason for the Web worker creating a new Class Instance every time a module is imported?

We are currently running a time-consuming function on a web worker. In addition, we have a Dispatcher Class that creates a single instance for other classes to utilize, as shown below:

class Dispatcher {
    constructor() {
        console.log("calling");
        this.events = {};
    }
//some code
}
const dispatcher = new Dispatcher();
export default dispatcher;

The above module has been imported into another file named DataManager Class at the beginning:

import dispatcher from '../../utility/dispatcher';

export class DataManager {
  notifyRenderer = (data: ResultData): void => {
        dispatcher.dispatch(NOTIFY_EVENT, data);
  }
}

Within our web worker, a new instance of the DataManager Class is created, and the notifyRenderer method within the DataManager Class is triggered from there.

import { DataManager } from "./data-manager";
let dm: DataManager;

addEventListener('message', (e) => {
    if (!dm) {
        dm = new DataManager();
    }

    const res = dm.addOrUpdateData(e.data.input, true);
    dm.notifyRenderer(res);
    postMessage({ type: 'Dispatch', res });
}, false);

Additionally, I have included a screenshot displaying the console.log("calling") message appearing twice. The reason behind why the Dispatch class constructor is called multiple times remains unclear.

https://i.sstatic.net/MZuoc.png

I am seeking assistance in resolving this issue. Your help is highly appreciated.

Could the problem be related to how modules are being imported?

Here is a screenshot trace from the worker:

https://i.sstatic.net/IVsUj.png

Your support is greatly valued!

Answer №1

Everyone learns from their mistakes through practice, and I had a similar experience here.

Initially, everything seemed fine with my modules - the Dispatcher Class, Data Manager Class, and instantiation of a new worker thread. However, the issue arose because I mistakenly created a single instance of the Dispatcher Class at the end of that module, assuming that the resulting exports would be cached due to the file caching mechanism in mjs / require. I attempted to use import in both the main thread and worker thread, only to realize that each thread was creating its own module instance. (My mistake!)

I only became aware of this error after a helpful hint from bergi. The correct approach is to send data from the worker thread to the main thread using postMessage and listen on the main thread.

Data sent from the worker thread:

postMessage(dm.addOrUpdateData(e.data.input, true) as ResultData);

Listening on the main thread:

this.worker.onmessage = (e: MessageEvent) => {
            if (!e.data) return;
            dispatcher.dispatch(NOTIFY_EVENT, e.data);
        };

To learn more about Realms and find helpful resources, visit:

  • How to understand JS realms

  • ES6 import duplicates?

Thank you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to enhance composability by utilizing React higher-order functions

Referring to the section titled "Convention: Maximizing Composability" in the React tutorial (link: https://reactjs.org/docs/higher-order-components.html#convention-maximizing-composability): // connect is a function that returns another function const enh ...

What benefits does NewRelic offer?

We are looking for a way to monitor events within our application and send the data to a monitoring server such as NewRelic. Our goal is to set up alerts based on this custom data. For instance, we would like to receive an alert if an event does not occur ...

"No location information is available" regardless of the input provided

Despite my efforts to utilize intl for formatting purposes, I consistently encounter the error message: ReferenceError: No locale data has been provided for this object yet I've experimented with various approaches such as: new Intl.NumberFormat( ...

What sets apart defining a function in ReactJS using only parentheses versus curly braces within parentheses?

As a newcomer to React, I encountered an interesting application that had functions defined in two different ways. One style was async function (a, b) => {//body}, which I found easy to understand. However, another set of functions followed the struct ...

The initial page in jqgrid may show rowobject value as undefined, but subsequent pages will display the correct rowObject values

While working with jqgrid-4.8, I encountered an issue where the rowObject value is coming up as undefined in the first page but values are received in subsequent pages when using rowObject.name. However, if rowObject[0] is used, the values of rowObject are ...

Struggling to successfully compile and release my Typescript library with webpack or TSC

I've developed a library that uses rx streams to track the state of an object, and now I'm looking to share it with the npm community. You can find the code on my Github repository. My goal is to compile the library into a single Javascript fil ...

Cross domain tracking pixel implemented using ASP.NET, jQuery, and AJAX technology

Currently, I have a page tracking system that uses $.post(PAIRS-DATA) in JavaScript to send collected information back to the server and load as a tracking pixel. finally { //tracking pixel Response.ContentType = "i ...

Dynamic Pagination with MUI Counting

I'm currently utilizing mui react for my current project. Within the Pagination component, I am required to input the count in order to display the total number of pages. For example, with a total of 27 products, and each page displaying 20 products ...

The autofocus feature does not function properly in an input tag that is not located within a form element

Is there a way to set the autofocus property in an input element that is not part of a form? I have tried adding the "autofocus" attribute to the input tag but it doesn't seem to be working. <div> //I have added the autofocus property her ...

Unable to produce audio from files

Attempting to incorporate sound files into my project using https://github.com/joshwcomeau/redux-sounds but encountering difficulties in getting it to function. Below is the code snippet I utilized for setup. Unsure if webpack is loading the files correctl ...

What could be causing the Monster model to not appear when using the glTFLoader in three.js on iOS?

-Details- three.js version : r84 (current version) Device : iPad Air2 iOS version : 10.0.2 Browser : Chrome, Safari -glTFLoader- URL : Monster -> NOT visible The rest -> visible Why am I asking this question? I have encountered a similar is ...

Fetching the Three.js mesh from the loader outside the designated area

Currently, I am immersed in a project that involves Three.js. The challenge I am facing is trying to access the mesh (gltf.scene) in the GLTF load from an external source. However, whenever I attempt to console.log outside of the loader, it shows up as und ...

Access information from multiple div elements using JavaScript data-attributes

Having trouble retrieving data-attribute values from multiple divs with the same class when clicked. The goal is to display the data value of the clicked div. function playSound(e) { const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`) ...

Opera does not support Ajax functionality

My ajax script is not functioning properly in Opera browser, although it works fine on other major browsers. $(function() { $("a").on('click', function(e) { var href = $(this).attr('href'); $.ajaxSetup({ beforeSend:fu ...

Guidelines on declining a pledge in NativeScript with Angular 2

I have encountered an issue with my code in Angular 2. It works fine in that framework, but when I tried using it in a Nativescript project, it failed to work properly. The problem arises when I attempt to reject a promise like this: login(credentials:Cr ...

Linking asynchronous functions does not function properly

I've been attempting to link two asynchronous functions together, but it appears that the second function is running before the first one. Below is the code snippet: function performAction(e) { const ZIP = document.getElementById('zip').valu ...

What is the best way to trigger the closing of a Bootstrap (version 5.2) Modal using JavaScript

In order to complete my school project, I decided to create a modal using Bootstrap in HTML. Inside the modal, there is a prompt that needs to be checked from JavaScript. How can I close the Modal from JavaScript? This way, if the prompt is valid, I can sa ...

Dealing with React Native text overflowing beyond the screen width when using FlexWrap

I'm currently working on implementing a component in react native that consists of a row containing and components, but I'm struggling to achieve the desired outcome. Here's my current code: <View style={{ flexDirection: ...

if statement not recognizing data returned from PHP function

I'm currently working with a function that is being used for an AJAX query: var formData = $(this).serialize(); //store form names and values in an array called 'formData' $.get('filtertest.php',formData,processData); //jQ ...

Is it possible to redirect any web traffic using an authentication script?

Scenario: I'm currently working on a social networking project and I'm looking for a way to validate every redirect or refresh by directing the user through another script before reaching their final destination. I've considered using a &apo ...