window.MessageChannel也是浏览器提供的一个异步操作的API,属于宏任务
这个api会创建一个管道,管道的两端分别代表一个messagePort,都能够通过portMessage向对方发送数据,通过onmessage来接受对方发送过来的数据 基本使用
const ch = new MessageChannel()
const port1 = ch.port1
const port2 = ch.port2
port1.onmessage = function(d) {
console.log(`port1接收的消息是:${d.data}`)
}
port2.onmessage = function(d) {
console.log(`port2接收的消息是:${d.data}`)
}
port1.portMessage('port1发送的消息')
port2.portMessage('port2发送的消息')
应用场景 让两个web worker可以通过MessageChannel通信,即实现多线程通信
<script>
var w1 = new Worker("worker1.js");
var w2 = new Worker("worker2.js");
var ch = new MessageChannel();
w1.postMessage("port1", [ch.port1]);
w2.postMessage("port2", [ch.port2]);
w2.onmessage = function(e) {
console.log(e.data);
}
</script>
====worker1.js
self.onmessage = function(e) {
const port = e.ports[0];
port.postMessage("this is from worker1")
}
====worker2.js
self.onmessage = function(e) {
const port = e.ports[0];
port.onmessage = function(e) {
postMessage(e.data)
}
}
|