网络工作者是否有某种负载事件?

问题描述 投票:1回答:1

当尝试使用广播频道在主脚本和工作者之间进行通信时,我遇到了一些问题。我在主脚本中有以下代码:

const channel = new BroadcastChannel('my_bus');
const worker = new Worker('worker.js');
const secondWorker = new Worker('second-worker.js');

channel.postMessage('1000');

以及两个工人中的类似代码:

const bc = new BroadcastChannel('my_bus');

bc.onmessage = () => {
  console.log('worker get length');
}

问题是当主脚本发出的消息,工作者尚未加载时,所以他们跳过了消息。我很确定,因为如果我做这样的事情,它可以正常工作:

setTimeout(() => {
  channel.postMessage('1000');
}, 100)

有没有办法在工作脚本加载后触发回调?

javascript web-worker
1个回答
1
投票

根据最后的评论,我会写下我的建议作为答案:

您可以让工作人员在加载时发出消息,并在主脚本上侦听该消息。这通常是我们对网络工作者做的事情:他们向主线程发出一条消息,说“我准备接收东西”。

可能的实现可能是:

// assumes the first `message` from workers is always the "loaded" ones
const loaded = w =>
  new Promise(r => w.addEventListener("message", r, { once: true }));

// Code runs inside async function, so we can use `await`
async function main() {
  const channel = new BroadcastChannel("my_bus");
  const worker = new Worker("worker.js");
  const secondWorker = new Worker("second-worker.js");

  await Promise.all([
    loaded(worker), 
    loaded(secondWorker)
  ]);

  // this will be post only once all the workers have been loaded
  channel.postMessage("1000");
}

// call the main function
main();

工人的代码如下:

const bc = new BroadcastChannel("my_bus");

bc.onmessage = () => {
  console.log("worker get length");
};

postMessage("loaded");
© www.soinside.com 2019 - 2024. All rights reserved.