【问题标题】:how do I return a value from a worker for a function in Javascript在 Javascript 中,如何从 worker 返回一个函数的值
【发布时间】:2023-01-27 12:57:21
【问题描述】:

我有一个产生工人的功能

function fetchFile(mes) {

    const worker = new Worker('worker.js');
    worker.postMessage(mes);

    //somehow return the message returned by the worker
}

工人.js:

self.onmessage = function (msg) {
    //some complex calculations
}

我想返回工作人员为该函数计算的值

有没有办法做到这一点?

【问题讨论】:

标签: javascript function worker


【解决方案1】:

在工人

self.onmessage = function (msg) {
  //some complex calculations
  postMessage(workerResult);
}

在主应用程序中

const worker = new Worker('worker.js');
worker.onmessage = (e) => {
  result.textContent = e.data;
  console.log('Message received from worker');
}
worker.postMessage(mes);

【讨论】:

    猜你喜欢
    • 2019-11-05
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 2014-08-31
    • 2011-04-04
    相关资源
    最近更新 更多