@Chanu_Sukarno의 코드를 확장하면 작업자 함수 (또는 문자열)를이 함수에 전달하기 만하면 웹 작업자 내에서 실행됩니다.
async function doWorkerTask(workerFunction, input, buffers) {
let fnString = '(' + workerFunction.toString().replace('"use strict";', '') + ')();';
let workerBlob = new Blob([fnString]);
let workerBlobURL = window.URL.createObjectURL(workerBlob, { type: 'application/javascript; charset=utf-8' });
let worker = new Worker(workerBlobURL);
return await new Promise(function(resolve, reject) {
worker.onmessage = function(e) { resolve(e.data); };
worker.postMessage(input, buffers);
});
}
다음은 사용 방법의 예입니다.
function myTask() {
self.onmessage = function(e) {
self.postMessage("my response");
self.close();
}
}
let output = await doWorkerTask(myTask, input, inputBuffers);
에서 nodejs , doWorkerTask
다음과 같습니다 :
async function doWorkerTask(workerFunction, input, buffers) {
let Worker = require('webworker-threads').Worker;
let worker = new Worker(workerFunction);
return await new Promise(function(resolve, reject) {
worker.onmessage = function(e) { resolve(e.data); };
worker.postMessage(input, buffers);
});
}