Skip to content

Instantly share code, notes, and snippets.

@Yoric
Created April 20, 2015 09:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yoric/c710b97dd55f98f8f0e3 to your computer and use it in GitHub Desktop.
Save Yoric/c710b97dd55f98f8f0e3 to your computer and use it in GitHub Desktop.
Making a PromiseWorker that can shutdown
let myWorker = {
//
// Worker initialization
//
get worker() {
if (this._worker) {
return this._worker;
}
// Otherwise, initialize PromiseWorker.
// TODO
},
_worker: null,
//
// Sending a message to the worker
//
post: function(...msg) {
if (this.promiseShutdownComplete) {
return Promise.reject(new Error(`Too late to send message ${msg}`));
}
return this.worker.post(...msg);
},
function shutdown() {
if (this._promiseShutDownComplete) {
// Shutdown has already started
return this._promiseShutdownComplete;
}
if (this._worker) {
// The worker has never been initialized
return this._promiseShutdownComplete = Promise.resolve();
}
return this._promiseShutdownComplete = this._worker.post(/*some message that will trigger shutdown*/);
},
// Initially, `null`. Once we have started the shutdown sequence,
// a promise that will resolve only one shutdown is complete.
_promiseShutdownComplete: null,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment