javascript:worker synchronization

邮差的信 提交于 2021-01-28 21:52:05

问题


I am working on HTML5 web worker and I made a function that spawn few workers and return the result, but problem is that it returns the value before the worker updates the result. So I want to delay return statement until all results are received

for (i = 0; i < array1_rows; i++)
{
    var worker = new Worker('json.js');
    worker.postMessage(arr1[i]);
    worker.postMessage(arr2);
    worker.postMessage(i);

    worker.onmessage = storeResult;
}

/////////////////////////////////

return result;

So I just want to delay that return statement until result are received. Plz help me on how to use the yield in java script.


回答1:


Like the comment points out - Web Workers work asynchronously (think of how AJAX works)

You can use an asynchronous semaphore to yield only when they're all done

function doSomething(callback){
    var counter = array1_rows;
    for (i = 0; i < array1_rows; i++)
    {
        var worker = new Worker('json.js');
        worker.postMessage(arr1[i]);
        worker.postMessage(arr2);
        worker.postMessage(i);

        worker.onmessage = function(){
            storeResult.apply(arguments);//call it the same way it was called before.
            counter--;
            if(counter === 0){ // all workers returned
                callback(result); //or whatever you're updating in storeResult
            }
        };
    }
}

Now you can call it like:

doSomething(function(result){
    console.log(result); //this will print the correct result.
});

For more information about how JS async operations work I recommend this ajax related question that includes a description of the problem and how to approach it.,



来源:https://stackoverflow.com/questions/18395319/javascriptworker-synchronization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!