我试图想出一种在网络工作者脚本中调用函数并让它们将值返回到主脚本的好方法,我发现很难想出一些可扩展的东西,因为它是异步的并且通过消息传递,任何帮助将不胜感激。这是我的网络工作者脚本...
self.addEventListener('message', function(e) {
var data = e.data;
switch (data.cmd) {
case 'call' :
self[data.funcName](data.args);
break;
default:
self.postMessage('Unknown command: ' + data.msg);
};
}, false);
function testWorkerFunction(args) {
self.postMessage({'cmd': 'call', 'funcName': 'testClientFunction', 'args': args});
}
这是我的主要脚本。
$(function() {
var someOtherVal;
worker = new Worker('js/workers/uc-main-worker.js');
worker.addEventListener('message', function(e) {
console.log('Worker said: ', e.data);
var data = e.data;
switch (data.cmd) {
case 'call' :
self[data.funcName](data.args);
break;
default:
console.log('Unknown command');
break;
};
}, false);
worker.onerror = function(e){
throw new Error(e.message + " (" + e.filename + ":" + e.lineno + ")");
};
/* This is the bit I need some help with, how I can return a value back here */
var someVal = messageWorker({'cmd': 'call', 'funcName': 'testWorkerFunction', 'args': 'hello'});
//Not sure how to get a value back without invoking a function in the main script because I have to use messaging.
});
function messageWorker(message) {
worker.postMessage(message);
}
function testClientFunction(args) {
//Simply storing it as a global var.
someOtherVal = args;
}
希望从我的代码中你明白我在追求什么,目前我可以获得 testWorkerFunction 返回的值,但只能通过调用另一个函数或将其存储为全局变量。