web-worker-helper
Version:
Utilities for running tasks on worker threads
48 lines (47 loc) • 1.56 kB
JavaScript
import { assert } from '../utils/env-utils/assert';
/**
* Represents one Job handled by a WorkerPool or WorkerFarm
*/
var WorkerJob = /** @class */ (function () {
function WorkerJob(jobName, workerThread) {
var _this = this;
this.name = jobName;
this.workerThread = workerThread;
this.isRunning = true;
this.resolve = function () { };
this.reject = function () { };
this.result = new Promise(function (resolve, reject) {
_this.resolve = resolve;
_this.reject = reject;
});
}
/**
* Send a message to the job's worker thread
* @param data any data structure, ideally consisting mostly of transferrable objects
*/
WorkerJob.prototype.postMessage = function (type, payload) {
this.workerThread.postMessage({
source: 'Main thread', // Lets worker ignore unrelated messages
type: type,
payload: payload,
});
};
/**
* Call to resolve the `result` Promise with the supplied value
*/
WorkerJob.prototype.done = function (value) {
assert(this.isRunning, 'WorkerJob isRunning false.');
this.isRunning = false;
this.resolve(value);
};
/**
* Call to reject the `result` Promise with the supplied error
*/
WorkerJob.prototype.error = function (error) {
assert(this.isRunning, 'WorkerJob isRunning false.');
this.isRunning = false;
this.reject(error);
};
return WorkerJob;
}());
export default WorkerJob;