wilk / microjob

A tiny wrapper for turning Node.js worker threads into easy-to-use routines for heavy CPU loads.
https://wilk.github.io/microjob/
MIT License
2.02k stars 47 forks source link

Microjob doesn't work with typescript #75

Open adam-arold opened 2 years ago

adam-arold commented 2 years ago

When I try to run the example using typescript:

(async () => {
    try {
        // start worker pool
        await start();

        // this function will be executed in another thread
        const res = await job(async () => {
            let i = 0;
            for (i = 0; i < 1000000; i++) {
                for (let j = 0; j < 1000000; j++) {
                    for (let k = 0; k < 1000000; k++) {
                        http.get("www.google.it");
                    }
                }
            }
            return i;
        });
        console.log(res); // 1000000
    } catch (err) {
        console.error(err);
    }
})();

I get:

ReferenceError: tslib_1 is not defined
    at eval (eval at <anonymous> ([worker eval]:11:5), <anonymous>:8:37)
    at __executor__ (eval at <anonymous> ([worker eval]:11:5), <anonymous>:10:12)
    at MessagePort.<anonymous> ([worker eval]:13:27)
    at MessagePort.[nodejs.internal.kHybridDispatch] (internal/event_target.js:399:24)
    at MessagePort.exports.emitMessage (internal/per_context/messageport.js:18:26)
    at MessagePort.callbackTrampoline (internal/async_hooks.js:130:17)

If I run the code from javascript it works. Is there a solution for this? ☝️

adam-arold commented 2 years ago

I tried to reduce this and it seems that the problem is the async function. This fails:

try {
    // start worker pool
    await start();

    // this function will be executed in another thread
    const res = await job(async () => {
        return 1;
    });
    console.log(res);
} catch (err) {
    console.error(err);
}

while this successfully returns 1:

try {
    // start worker pool
    await start();

    // this function will be executed in another thread
    const res = await job(() => {
        return 1;
    });
    console.log(res);
} catch (err) {
    console.error(err);
}

I tried looking up the error message but all I found were 2 GitHub issues that were unactionable and closed. Do you have a working example with typescript?