Skip to content

Instantly share code, notes, and snippets.

@preco21
Last active May 25, 2016 01:03
Show Gist options
  • Save preco21/5a8e152070d1054b4f00 to your computer and use it in GitHub Desktop.
Save preco21/5a8e152070d1054b4f00 to your computer and use it in GitHub Desktop.
Simple InlineWorker
import Promise from 'bluebird';
import EventEmitter from 'eventemitter3';
class InlineWorker {
constructor(source) {
if (typeof source != 'function') {
throw new TypeError('source must be a function');
}
if (this._worker) {
this.terminate();
}
let methodString = source.toString().trim().match(/{([\w\W]*?)}/)[1];
this._createWorker(methodString);
this._worker.addEventListener('message', (event) => this._messageHandler(event));
this._worker.addEventListener('error', (error) => this._errorHandler(error));
}
start(data) {
if (!this._worker) {
throw new Error('Worker is not created');
}
return new Promise((resolve, reject) => {
this._worker.postMessage(data);
this.once('message', resolve);
this.once('error', reject);
});
}
terminate() {
if (!this._worker) {
throw new Error('Worker is not created');
}
this._worker.terminate();
this._worker = null;
URL.revokeObjectURL(this._workerBlob);
this._workerBlob = null;
}
_createBlobURL(source) {
let blob = new Blob([source]);
return URL.createObjectURL(blob);
}
_createWorker(blobURL) {
this._workerBlob = this._createBlobURL(blobURL)
this._worker = new Worker(this._workerBlob);
}
_errorHandler(error) {
this.emit('error', new Error(`${error.message} (${error.filename}:${error.lineno})`));
}
_messageHandler(event) {
this.emit('message', event.data);
}
}
mixinEventEmitter(InlineWorker);
function mixinEventEmitter(target) {
Object.assign(target.prototype, EventEmitter.prototype);
target.prototype.constructor = target;
}
export {
InlineWorker as default
};
@preco21
Copy link
Author

preco21 commented Oct 25, 2015

Usage:

(async () => {
  let worker = new InlineWorker(() => {
    onmessage = (event) => {
      postMessage(event.data * 2);
    };
  });

  let result = await worker.start(1234);

  console.log(result);
  worker.terminate();
})();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment