admin管理员组

文章数量:1289412

I have a NextJS application (App Router) which includes a Route Handler which triggers generation of a PDF. This process takes a while, which causes the main thread to stall.

The application runs as an Azure Container App and this causes the application to be terminated as the container app can't get any liveness response from it.

I've tried to offload the operation into a node.js worker thread. This seems to work but the problem is that the route handler exits prematurely. Do anyone know if is is possible to wait for the thread to finish (using e.g. await og Promise)?

The code I have so far is as follows:

export async function POST(req: NextRequest) {
    <snip>
      const worker = new Worker(
    /* webpackChunkName: "pdfGenerator.worker" */ new URL(
      '../../../../pdf/pdfGenerator.tsx',
      import.meta.url,
    ),
  );

  worker.postMessage(message);
  worker.on('message', (result: CreatePDFResponse) => {
    if (result.result === 'ok') {
      <Return response with PDF>
    } else {
      <return error>
    }
  });
  worker.on('error', (error) => {
    <return error>
  });
}

but I have not found a way to actually wait for the worker.no to fire, instead the route handler just exits.

本文标签: nodejsNextJS Route handlerwait for worker thread to finishStack Overflow