NodeJS 节点工作线程Promise的实现问题

e3bfsja2  于 2023-06-05  发布在  Node.js
关注(0)|答案(1)|浏览(157)

我试图做一个测试卸载任务到工作线程。
工作流程很简单,我有100个promise数组,每个promise将创建一个工作线程。
主线程将把索引传递给工作线程,工作线程将等待1.5秒,然后将索引返回给主线程。
main.js:

const { Worker } = require("node:worker_threads");

(async () => {
  await Promise.all(
    Array.from(Array(100), (x, i) => i).map(
      (i) =>
        new Promise((resolve, reject) => {
          const worker = new Worker("./worker.js");
          worker.postMessage(i);
          worker.on("message", (event) => resolve(event));
          worker.on("error", reject);
          worker.on("exit", (code) => console.log(`worker ${code} exited`));
        })
    )
  )
    .then((results) => console.log(results))
    .catch((err) => console.log(err));
})();

worker.js

const { workerData, parentPort } = require("node:worker_threads");

const setTimeoutPromise = (ms) => {
  return new Promise(async (resolve, reject) => {
    await setTimeout(() => {
      resolve();
    }, ms);
  });
};

onmessage = async (index) => {
  console.log(`receive index: ${index}`);
  await setTimeoutPromise(1500);
  parentPort.postMessage(`worker ${index} return`);
};

但是即使是Promise.all也没有返回结果,所有的工作线程都退出了,应用程序也完成了。
我怎么能像简单的promise那样等待所有的worker thread promise完成?

z6psavjg

z6psavjg1#

我认为这段代码只是创建了一个名为onmessage的变量,而不是分配监听器

onmessage = async (index) => {
  console.log(`receive index: ${index}`);
  await setTimeoutPromise(1500);
  parentPort.postMessage(`worker ${index} return`);
};

尝试使用以下命令:

parentPort.once('message', async (index) => {
  console.log(`receive index: ${index}`);
  await setTimeoutPromise(1500);
  parentPort.postMessage(`worker ${index} return`);
});

如果要侦听多个message事件,也可以使用on而不是once

相关问题