简体   繁体   English

从 webworker 发送消息并等待回复

[英]Send message from webworker and wait for reply

I am currently working with webworker and canvas for the first time and have a question about it.我目前是第一次与 webworker 和 canvas 合作,对此有疑问。

I have a webpage that needs to draw multiple elements on a canvas. When the canvas is full I want to create a new canvas and continue drawing on it.我有一个网页需要在canvas上绘制多个元素。当canvas已满时我想创建一个新的canvas并继续绘制。 I have outsourced the logic for drawing to a webworker that gets a list of elements and the current canvas (OffscreenCanvas).我已经将绘制逻辑外包给了一个获取元素列表和当前 canvas (OffscreenCanvas) 的网络工作者。 I would like to use a promise to send a message to the frontend in the webworker to create the new canvas and get it back as a response.我想使用 promise 向 webworker 的前端发送消息以创建新的 canvas 并将其作为响应取回。 Is there an elegant solution for this?有没有一个优雅的解决方案? I seem to have hit a block in my thinking.我的思路似乎遇到了障碍。

I think i found a solution:我想我找到了解决方案:

const WEBWORKER_INSTANCE = self; // DedicatedWorkerGlobalScope
const PROMISE_TIMEOUT = 1000;

function addNewPageCallback(pageCount: number): Promise<OffscreenCanvas> {
  return new Promise<OffscreenCanvas>((resolve, reject) => {
    let timeoutId = null;
    const id = `page#${pageCount + 1}`;

    WEBWORKER_INSTANCE.addEventListener('message', (event: MessageEvent<DrawCanvasEvent>) => {
      if (event.data.action === 'page-added') {
        const data = event.data as DrawCanvasAddPageResponseEvent;
        if (data.id === id) {
          clearTimeout(timeoutId);
          resolve(data.canvas);
        }
      }
    });

    const message: DrawCanvasAddPageRequestEvent = {
      action: 'add-page',
      id
    };
    postMessage(message);

    timeoutId = setTimeout(reject, PROMISE_TIMEOUT);
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM