这是旧的,但我在寻找不同的答案时正在查看它..
为什么不让工人处理自己的状态和终止呢?最初的问题询问如何让工作人员完成未完成的请求。所以让它完成它的请求并指示它何时完成。
如果 javascript 是这样的:
var eftWorker = undefined;
var StartWorker = function () {
if (eftWorker === undefined) {
eftWorker = new Worker('/scripts/ETEL.EftWorker.js');
eftWorker.addEventListener('message', function(e) {
EftWorkerResponseHandler(e.data);
}, false);
eftWorker.addEventListener('error', function (e) {
EftWorkerErrorResponseHandler(e);
}, false);
// i'm assuming we don't want to trigger start multiple times,
// so this is moved inside the IF.
eftWorker.postMessage({ cmd: eftCmdStart });
}
};
that.StopWorker = function () {
if (eftWorker !== undefined) {
eftWorker.postMessage({ cmd: eftCmdStop });
}
};
var EftWorkerResponseHandler = function (msg) {
try {
if (msg && msg === 'readyToTerminate') {
eftWorker.terminate();
eftWorker = undefined;
} else {
// handle other situations.
}
} catch (exception) { }
};
工人是这样的:
;(function(self, undefined) {
var receivedStopCmd = false;
self.addEventListener('message', function(e){
if (e.data.cmd === 'eftCmdStart') {
// kick off processing here
EftSendGetRequest('...');
}
if (e.data.cmd === 'eftCmdStop') {
// xhr might be in process, this just updates what
// the onload function does.
receivedStopCmd = true;
}
}, false);
var EftSendGetRequest = function(passedUrl) {
if (xmlHttpReq === undefined) {
xmlHttpReq = new XMLHttpRequest();
}
try {
xmlHttpReq.open("GET", passedUrl, false);
xmlHttpReq.onload = function(){
if (!receivedStopCmd) {
// post response and/or keep polling
self.postMessage('whatever the message is');
} else {
// (1) stop polling so no more
// requests are sent..if this
// requires doing anyhting
// (2) Send a message that this worker can be terminated.
self.postMessage('readyToTerminate');
}
};
xmlHttpReq.send();
} catch (e) { }
return xmlHttpReq.responseText;
};
})(self);
这将允许 XHR 进行自我管理。我当然没有运行这个..它只是我在这个问题上采取的方法的一个例子。