Skip to content

How to pass the params to the function? #7

@fredowashere

Description

@fredowashere

We made an hacky solution for this, hope you enjoy!

function execOutside(fnRef, input) {
    let strFn = fnRef.toString();
    const re = /function[^(]*\(([^)]*)\)/;
    const matched = strFn.match(re)[1];
    strFn = strFn.replace(re, "function ()");
    const str = `
self.onmessage = ({ data }) => {
    const [[replacer]] = data;
    (${strFn})();
    self.postMessage(data);
}`.replace("[[replacer]]", matched);

    return new Promise((resolve) => {
        const w = new Worker(URL.createObjectURL(new Blob([str])));
        w.onerror = (err) => console.error(err);
        w.onmessage = ({ data }) => resolve(data);
        w.postMessage(input);
    })
}

console.log(
    await execOutside(
        function (a) {
            a.test = "c";
            for (let i = 0; i < 5e9; i++) {}
            console.log(a.test);
        },
        { test: "test" }
    );
);

P.S.: Sorry for the necroposting xD

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions