worker.receiveMessageOnPort(port)
-
port
<MessagePort> | <BroadcastChannel> -
返回: <Object> | <undefined>
从给定的 MessagePort
接收消息。
如果没有消息可用,则返回 undefined
,否则返回具有单个 message
属性的对象,该对象包含消息负载,对应于 MessagePort
队列中最旧的消息。
const { MessageChannel, receiveMessageOnPort } = require('node:worker_threads');
const { port1, port2 } = new MessageChannel();
port1.postMessage({ hello: 'world' });
console.log(receiveMessageOnPort(port2));
// 打印: { message: { hello: 'world' } }
console.log(receiveMessageOnPort(port2));
// 打印: undefined
当使用此函数时,不会触发 'message'
事件,也不会调用 onmessage
监听器。
-
port
<MessagePort> | <BroadcastChannel> -
Returns: <Object> | <undefined>
Receive a single message from a given MessagePort
. If no message is available,
undefined
is returned, otherwise an object with a single message
property
that contains the message payload, corresponding to the oldest message in the
MessagePort
's queue.
const { MessageChannel, receiveMessageOnPort } = require('node:worker_threads');
const { port1, port2 } = new MessageChannel();
port1.postMessage({ hello: 'world' });
console.log(receiveMessageOnPort(port2));
// Prints: { message: { hello: 'world' } }
console.log(receiveMessageOnPort(port2));
// Prints: undefined
When this function is used, no 'message'
event is emitted and the
onmessage
listener is not invoked.