Search code examples
javascripthtmlweb-worker

Javascipt Web Worker with Multiple Array Arguments


I wish to pass two arrays to a JS Worker, process them in worker and reload the Page once the Processing is complete. However I am stuck with the Argument syntax. I am getting error : "No function was found that matched the signature provided"

var issueKeyArr = [1,2,3,3], executionIdArray = [4,5,5,6]
var myWorker = new Worker('zephyr-worker.js');

myWorker.onmessage = function(e) {
    console.log('Message received from worker ========== reload the page here');
}

myWorker.postMessage(JSON.stringify(issueKeyArr), JSON.stringify(executionIdArray));
console.log('Message posted to worker');

My "zephyr-worker.js" file :

onmessage = function(issueKeyArr, executionIdArray) {   
    console.log("worker called ========================");
    for (var i=0; i < issueKeyArr.length; i++)
    {
        var issueKey = issueKeyArr[i];
        var executionId = executionIdArray[i];
        // more processing here...
    }
     postMessage("done");
}

Solution

  • The syntax of postMessage is

    worker.postMessage(yourMessageData, [transfer]);

    Since you don't need to really transfer any object ownership, you don't need to care about the optional [transfer] part of the postMessage signature above.

    and the corresponding syntax of onmessage is

    myWorker.onmessage = function(messageEvent) { ... }

    with the messageEvent corresponding to an object that looks like {..., data: yourMessageData, ...}

    Another thing that you can see from this documentation and the example there is that you don't need to use JSON.stringify. Serialization of simple objects is already done automatically.

    So your code should become:

    var issueKeyArr = [1,2,3,3], executionIdArray = [4,5,5,6]
    var myWorker = new Worker('zephyr-worker.js');
    
    myWorker.onmessage = function(e) {
        console.log('Message received from worker ========== reload the page here');
    }
    
    myWorker.postMessage({issueKeyArr: issueKeyArr, executionIdArray: executionIdArray});
    console.log('Message posted to worker');
    

    with your "zephyr-worker.js" file :

    onmessage = function(messageEvent) {   
        console.log("worker called ========================");
    
        var issueKeyArr = message.data.issueKeyArr;
        var executionIdArray = message.data.executionIdArray;
    
        for (var i=0; i < issueKeyArr.length; i++)
        {
            var issueKey = issueKeyArr[i];
            var executionId = executionIdArray[i];
            // more processing here...
        }
         postMessage("done");
    }