1
    2
    3
    4
    5
    6
    7
    8
    9
   10
   11
   12
   13
   14
   15
   16
   17
   18
   19
   20
   21
   22
   23
   24
   25

content / test / data / run_async_code_on_worker.html [blame]

<!doctype html>
<title>Run async code on a worker helper</title>
<script>
const workerCode = `
onmessage = function(e) {
  let AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
  let receivedFunction = new AsyncFunction(e.data);
  receivedFunction().then(workerResult => {postMessage(workerResult);});
}
`
const workerBlob = new Blob ([workerCode], {type: 'text/javascript'});
const worker = new Worker(window.URL.createObjectURL(workerBlob));

async function runOnWorkerAndWaitForResult(code) {
  worker.postMessage(code);
  return new Promise((resolve, reject) => {
    worker.onmessage = result => {
      resolve(result.data);
    }
    worker.onerror = error => {
      reject(error);
    }
  });
}
</script>