MessageChannel 类


worker.MessageChannel 类的实例代表异步的双向通信通道。 MessageChannel 没有自己的方法。 new MessageChannel() 产生具有 port1port2 属性的对象,其引用链接的 MessagePort 实例。

const { MessageChannel } = require('node:worker_threads');

const { port1, port2 } = new MessageChannel();
port1.on('message', (message) => console.log('received', message));
port2.postMessage({ foo: 'bar' });
// 从 `port1.on('message')` 监听器打印 received { foo: 'bar' }

Instances of the worker.MessageChannel class represent an asynchronous, two-way communications channel. The MessageChannel has no methods of its own. new MessageChannel() yields an object with port1 and port2 properties, which refer to linked MessagePort instances.

const { MessageChannel } = require('node:worker_threads');

const { port1, port2 } = new MessageChannel();
port1.on('message', (message) => console.log('received', message));
port2.postMessage({ foo: 'bar' });
// Prints: received { foo: 'bar' } from the `port1.on('message')` listener