类:MessageChannel
【Class: MessageChannel】
worker.MessageChannel 类的实例表示一个异步的双向通信通道。
MessageChannel 本身没有任何方法。使用 new MessageChannel() 会生成一个具有 port1 和 port2 属性的对象,这两个属性分别指向关联的 MessagePort 实例。
【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.】
import { MessageChannel } from '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'use strict';
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