Search code examples
javascriptarraysweb-worker

async pushing data into array as web worker returns result


I have developed code to perform operations by creating 5 web workers. I am simply sending integers to web workers to generate a sum and return a json object. I am pushing that result into an array. This array is stored in local storage once all web workers complete their task. The problem is array stored in local storage doesn't store values in the order returned by each web worker. If web worker returned the value first then the array must contain its value at zero index which means async operation is not being met. How do I go about doing this?

Here's my code for .js file:

      window.onload = init;
   var running = 0;
    var arr=[1,1001,2001,3001,4001];
   var sec=[1000,2000,3000,4000,5000]
   var results=[];
    function init() {

      sendworker();
    }


   function sendworker()
    {

     var n, worker;
     display("Starting workers...");

     for (n = 0; n <5; ++n) {
    workers = new Worker("jsonWorker.js");
    workers.onmessage = workerDone;
    workers.postMessage({id: n, start: arr[n],end:sec[n]});
    ++running;

     }

}

  function workerDone(e) {
    --running;
    display("Worker  " + e.data.id + " is done, sum of integers between: "+e.data.start+ "&"+e.data.end+"=" + e.data.sum);
    results.push(e.data.sum);

    if (running === 0) { // <== There is no race condition here, see below
        display("All workers complete");
        window.localStorage.setItem("Results", JSON.stringify(results));

    }
}

function display(msg) {
    var p = document.createElement('p');
    p.innerHTML = String(msg);
    document.body.appendChild(p);
}

// My code for web worker.js

 this.onmessage = function(e) {
  var data = e.data;
  var a=data.start;
  var b=data.end;
  var c=0;
  for (var i=a; i<= b; i++) {

     c=c+i;

  }
  this.postMessage({id: e.data.id,start:a,end:b,sum: c});

};

enter image description here

enter image description here

In the picture worker 0 returned result first so its data should be on the second index of array stored in local storage but it is not.


Solution

  • Use their id as offset ( to get the results sorted after when they were started):

    results[e.data.id] = e.data.sum;