无法在 worker_threads 中调用 class 实例方法

Can't call a class instance method inside worker_threads

我正在努力 node.js 'worker_threads'。

所以我想做的是将我的自定义 class 的几个实例传递到工作线程中。 实例通过一些唯一的序列号分配给映射。 所以基本上,我有一个类型的地图 - .

我的工作器实现如下所示:

Class 方法 运行 设置一个辅助服务:

public static runService = (workerData:any) => {
        return new Promise((resolve, reject) => {
            const route = path.join(__dirname, '/worker.js');
            const worker = new Worker(route, { workerData });
            worker.on('message', resolve);
            worker.on('error', reject);
            worker.on('exit', (code:number) => {
            if (code !== 0)
                reject(new Error(`Worker stopped with exit code ${code}`));
            })
        })
    }

工人本身:

const { workerData, parentPort } = require('worker_threads')

const instance = new Counter();
const {items, myMap} = workerData;
const pResponseList:Promise<any>[] = [];

items.map((item: Item) => {
    pResponseList.push(
        instance.count(item, myMap.get(item._id)!)
    );
});

Promise.all(pResponseList).then(res => parentPort.postMessage(res));

并且每当我在 'count' 方法中尝试 运行 item 实例中的方法时,它都会抛出一个错误

myMapEntry.myCustomInstanceMethod is not a function

我试图 console.log() 我的实例的内容,然后才将它传递给 .count() 方法,一切都已正确解决。

相同的模式 运行 在 worker 实例之外完美无缺。

任何人都可以帮助我找出这段代码中可能存在的错误吗?

您不能传递函数(例如 classes 的实例将不起作用,至少它们的方法不会)- 您只能传递可序列化的数据。

https://nodejs.org/api/worker_threads.html#worker_threads_worker_workerdata

An arbitrary JavaScript value that contains a clone of the data passed to this thread’s Worker constructor.

根据 HTML 结构化克隆算法,就像使用 postMessage() 一样克隆数据。

那我们就去HTML structured clone algorithm

Things that don't work with structured clone Function objects cannot be duplicated by the structured clone algorithm; attempting to throws a DATA_CLONE_ERR exception.

您能否使用序列化数据重建 class 的实例,调用您的方法,然后 return 将序列化数据返回给父线程?