javascript - Call function inside worker thread nodejs - Stack Overflow

Here's my worker:const Worker = require('worker_threads');const worker = new Worker(&qu

Here's my worker:

const Worker = require('worker_threads');
const worker = new Worker("function hello () { console.log('hello world');}", { eval: true })
worker.hello() // not correct

I would like to call hello()

How do I do this?

Here's my worker:

const Worker = require('worker_threads');
const worker = new Worker("function hello () { console.log('hello world');}", { eval: true })
worker.hello() // not correct

I would like to call hello()

How do I do this?

Share Improve this question asked Apr 2, 2020 at 18:17 HarryHarry 55.1k76 gold badges187 silver badges270 bronze badges 1
  • If you look at the docs, you'll see that's not how they require Worker – blex Commented Apr 2, 2020 at 18:22
Add a ment  | 

2 Answers 2

Reset to default 5

Threads municate through passing messages back and forth, for instance:

worker.postMessage("say hello");

Your worker would set up a listener for the message event, and receive the message as the value property of that eevnt:

// In the worker
const { isMainThread, parentPort } = require('worker_threads');
if (!isMainThread) {
    parentPort.on("message", e => {
        // Dispatch here. For instance:
        if (e.value === "say hello") {
            hello();
        }
    };
}
function hello() { /*...*/ }

There's a lot more to messaging back and forth, details in the worker documentation.

you can use worker-messenger on npm to write that style:

import { Worker } from 'worker_threads'
import { ParentMessenger } from 'worker-messenger'
const test = async () => {
    const results = await messenger.callWorker('testFunction_2', 'args', timeout)
    console.log({results});
}
test()

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745161765a4614421.html

相关推荐

  • javascript - Call function inside worker thread nodejs - Stack Overflow

    Here's my worker:const Worker = require('worker_threads');const worker = new Worker(&qu

    3小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信