Search code examples
javascriptweb-worker

Web worker function return response two times for a single call


I am using web worker in my application to execute some operations. Calling the web worker function from my js file only once with parameter. But its executing twice, first time with out parameter (parameter 'undefined'). And second time with parameter. What am I doing wrong?

js File

function f1(data) {
  console.log('function called');
  ww.postMessage({ action: 'name', data: { params: data } });
  ww.onmessage = function(event) {
    res = event.data;
    console.log(event.data);
  };
}

in web worker file

self.addEventListener('message', function(e) {
  functionName = e.data.action;
  data = e.data.data;
  switch (functionName) {
    case 'name':
      var res = processData(data);
      self.postMessage(res);
      break;
  }
});

function processData(data) {
  if (data.params != undefined) {
    console.log('parameter', data);
    //some code to run
    //finally
    return res;
  }
}

The out put I am getting in console

function called 
undefined // from event.data
parameter data //actual data I passed
{} //event.data  result of the action

Why is the parameter data not consoled the first time.


Solution

  • You have some smaller errors in your code that prevents a smooth execution

    1. you forgot to declare functionName and data as variables

    self.addEventListener('message', function(e) {
      var functionName = e.data.action;
      var data = e.data.data;
      switch (functionName) {
        case 'name':
          var res = processData(data);
          self.postMessage(res);
          break;
      }
    });
    

    2. Your return value was never declared as variable as well

    function processData(data) {
      if (data.params !== undefined) {
        console.log('parameter', data);
        //some code to run
        //finally
        return data;
      }
    }
    

    3. In your callback function you did not declare res as variable as well

    var ww = new Worker('worker.js');
    
    function f1(data) {
      console.log('function called');
      ww.postMessage({ action: 'name', data: { params: data } });
      ww.onmessage = function(event) {
        var res = event.data;
        console.log(res);
      };
    }
    
    f1('test');
    

    I strongly advise to use a sophisticated IDE such as PHPStorm or WebStorm which give hints on such smaller (and bigger) errors, because they reference the whole application and therefore know where something is called and defined.