singletonWorker
code:script.js
export class singletonWorker {
constructor(source) {
this._worker = new Worker(source);
this._isRunning = false;
this._buffer = [];
}
delegate(...args) {
return new Promise(async resolve => {
if(this._isRunning) {
//console.log(The Web Worker is running, so this action is pending.);
this._buffer.forEach(pair => pair.resolve({state: 'cancelled'}));
return;
}
//console.log('Start running...');
this._isRunning = true;
resolve(await this._post(...args));
if (this._buffer.length > 0) {
this._buffer.forEach(async pair => await pair.resolve(await this._post(...pair.args)));
this._buffer = [];
}
this._isRunning = false;
});
}
async _post(...args) {
this._worker.postMessage(...args);
return new Promise(resolve => {
const callback = e => {
resolve({data: e.data, state: 'fullfilled'});
this._worker.removeEventListener('message', callback);
};
this._worker.addEventListener('message', callback);
});
}
}