UNPKG

web-worker-helper

Version:

Utilities for running tasks on worker threads

50 lines (49 loc) 1.67 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var assert_1 = require("../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) { (0, assert_1.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) { (0, assert_1.assert)(this.isRunning, 'WorkerJob isRunning false.'); this.isRunning = false; this.reject(error); }; return WorkerJob; }()); exports.default = WorkerJob;