如何将函数传递给JavaScript Web Worker

时间:2012-08-10 22:11:14

标签: javascript web-worker

我想通过postMessage()将函数(或函数)传递给Web worker,因为我不能引用常规文件。

要关闭Web工作者,我将对象URL(从Blob创建)传递给Worker构造函数。然后我传递了一条消息,但到目前为止没有运气在消息中添加功能。

(JSON)消息不能直接包含函数(如规定的here),虽然理论上允许使用importScripts,但到目前为止我还没有在Chrome或Firefox中使用过它。

html文件的正文:

<div id="divText">1234</div>
<script>
    var greeter = function greet(name) {
        return "hello " + name;
    };
    function webWorkerWorker() {
        self.postMessage("started1");
        self.onmessage = function(event) {
            importScripts(event.data.content);
            self.postMessage("importScripts success");
            var result = greeter("john");
            self.postMessage(result);
        };
    }
    var functionBody = mylib.extractFunctionBody(webWorkerWorker);
    var functionBlob = mylib.createBlob([functionBody]);
    var functionUrl = mylib.createObjectURL(functionBlob);

    var functionBody2 = mylib.extractFunctionBody(greeter);
    var functionBlob2 = mylib.createBlob([greeter]);
    var functionUrl2 = mylib.createObjectURL(functionBlob2);

    var worker = new Worker(functionUrl);
    worker.onmessage = function(event) {
        document.getElementById("divText").innerHTML = event.data;
    }
    worker.postMessage({
                type: "init",
                content: functionUrl2
            });
</script>

目前,它会将divText值设置为“importScripts success”。

我做错了吗?还有另一种方法可以将函数传递给Web worker吗?或者是不可能的?

3 个答案:

答案 0 :(得分:5)

事实证明这种方法很好,我的工作人员只有一个错误:

var result = greeter("john");

应该是

var result = greet("john");

这是有意义的 - 我将greeter变量传递给worker,但是没有理由知道我传递的对象的变量名。

答案 1 :(得分:4)

对于那些正在寻找更通用答案的人: 这是一个插件,它允许你在一个线程中执行你的javascript代码的任何功能。

http://www.eslinstructor.net/vkthread/

将其视为“功能外包”。您将任何函数作为参数传递给插件,并获得回调结果。您还可以“外包”对象的方法,使用dependecies,anonymous function和lambda。

享受。

- 瓦迪姆

答案 2 :(得分:0)

是的,当然有可能,我实施了它

这是一个执行通用工作程序的承诺

/*
    @data.context, The context where the callback functions arguments are, ex: window
    @data.callback, ["fn_name1", "fn_name2", function (fn1, fn2) {}]
        The callback will be executed, and you can pass other functions to that cb
    @worker_url string url of generic web worker
*/
function genericWorker(worker_url, data) {
    return new Promise(function (resolve, reject) {

        if (!data.callback || !Array.isArray(data.callback))
            return reject("Invalid data")

        var callback = data.callback.pop()
        var functions = data.callback
        var context = data.context

        if (!worker_url)
            return reject("Worker_url is undefined")

        if (!callback)
            return reject("A callback was expected")

        if (functions.length>0 && !context)
            return reject("context is undefined")

        callback = fn_string(callback) //Callback to be executed
        functions = functions.map((fn_name)=> { return fn_string( context[fn_name] ) })

        var worker = new Worker(worker_url)

        worker.postMessage({ callback: callback, functions: functions })

        worker.addEventListener('error', function(error){
            return reject(error.message)
        })

        worker.addEventListener('message', function(e) {
            resolve(e.data)
            worker.terminate()

        }, false)


        //From function to string, with its name, arguments and its body
        function fn_string (fn) {
            var name = fn.name
            fn = fn.toString()

            return {
                name: name,
                args: fn.substring(fn.indexOf("(") + 1, fn.indexOf(")")),
                body: fn.substring(fn.indexOf("{") + 1, fn.lastIndexOf("}"))
            }
        }

    })
}

通用工作人员文件worker_for_anything.js

self.addEventListener('message', function(e) {    
    var worker_functions = {} //Functions used by callback
    var args = [] //Arguments of the callback

    for (fn of e.data.functions) {
        worker_functions[fn.name] = new Function(fn.args, fn.body)
        args.push(fn.name)
    }

    var callback = new Function( e.data.callback.args, e.data.callback.body) //Callback passed and ready to be executed    
    args = args.map((fn_name) => { return worker_functions[fn_name] }) //FUnctions loaded as arguments
    var result = callback.apply(null, args) //executing callback with function arguments
    self.postMessage( result )

}, false)

使用它:)

var data = {
    context: window, //the context of the functions passed, ex: window for blockCpu
    callback: ["blockCpu", function (bla) {
        bla(7000) //blocking for 7000 ms
        return "bla" //This return is catched in the promise
    }]
}

genericWorker("/worker_for_anything.js", data)
    .then(function (result){
        console.log("result", result)

    }).catch((error)=> { console.log(error) })

//random blocking function
function blockCpu(ms) {
    var now = new Date().getTime();
    var result = 0
    while(true) {
        result += Math.random() * Math.random();
        if (new Date().getTime() > now +ms)
            return;
    }   
}