我目前有一个 web worker 试图接受 1 个参数
wworker = postMessage([textCoords[0], textCoords[1], latlong[0], latlong[1]]);
wworker.addEventListener('message', findDistance);
但是,控制台上不断弹出一个错误:“未捕获的类型错误:无法在‘窗口’上执行‘postMessage’:需要 2 个参数,但只有 1 个存在。” AFAIK postMessage 第二个参数是可选的。
这是我的 worker.js
var distance;
function findDistance(event) {
var destinationLat, destinationLon, originLat, originLon, haversineLat, haversineLon, thetaLat, thetaLon;
destinationLat = event.data[0] * (Math.PI/180);
destinationLon = event.data[1] * (Math.PI/180);
originLat = event.data[2] * (Math.PI/180);
originLon = event.data[3] * (Math.PI/180);
thetaLat = destinationLat - originLat;
thetaLon = destinationLon - originLon;
haversineLat = (1-Math.cos(thetaLat))/2;
haversineLon = (1-Math.cos(thetaLon))/2;
distance = 2 * 6376 * Math.asin(Math.sqrt(haversineLat + Math.cos(originLat) * Math.cos(destinationLat) * haversineLon));
postMessage(distance);
}
self.addEventListener('message', findDistance);
最佳答案
您没有在 Worker
上调用 .postMessage()
;您还在 for
循环的每次迭代中附加了一个新的 message
事件。将 wworker.addEventListener('message', findDistance);
移到 for
循环之外,在 for< 中调用
循环wworker.postMessage()
/
var wworker = new Worker("assets/scripts/webworker.js");
wworker.addEventListener('message', findDistance);
for(i=0;i<lines.length;i++){
var temp = lines[i].split(",");
wworker.postMessage([textCoords[0], textCoords[1], latlong[0], latlong[1]]);
textCoords.shift();
textCoords.shift();
}
关于javascript - 无法在 'postMessage' : 2 arguments required, 上执行 'Window' 但只有 1 个存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42614150/