singletonWorker-2
Promiseで包むようにた
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.resolve?.({state: 'cancelled'});
this._buffer = {resolve, args};
return;
}
//console.log('Start running...');
this._isRunning = true;
resolve(await this._post(...args));
if (this._buffer.resolve) {
this._buffer.resolve(await this._post(...this._buffer.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);
});
}
}