Fix worker bridge code

This commit is contained in:
Jake Archibald
2020-09-29 16:44:58 +01:00
parent b11ae0b8c7
commit db2d6f4ca6

View File

@@ -15,6 +15,8 @@ class WorkerBridge {
protected _worker?: Worker; protected _worker?: Worker;
/** Comlinked worker API. */ /** Comlinked worker API. */
protected _workerApi?: ProcessorWorkerApi; protected _workerApi?: ProcessorWorkerApi;
/** ID from setTimeout */
protected _workerTimeout?: number;
protected _terminateWorker() { protected _terminateWorker() {
if (!this._worker) return; if (!this._worker) return;
@@ -36,30 +38,32 @@ for (const methodName of methodNames) {
...args: any ...args: any
) { ) {
this._queue = this._queue this._queue = this._queue
// Ignore any errors in the queue
.catch(() => {}) .catch(() => {})
.then(async () => { .then(async () => {
if (signal.aborted) throw new DOMException('AbortError', 'AbortError'); if (signal.aborted) throw new DOMException('AbortError', 'AbortError');
let done = false;
signal.addEventListener('abort', () => {
if (done) return;
this._terminateWorker();
});
clearTimeout(this._workerTimeout);
if (!this._worker) this._startWorker(); if (!this._worker) this._startWorker();
const timeoutId = setTimeout(() => { const onAbort = () => this._terminateWorker();
this._terminateWorker(); signal.addEventListener('abort', onAbort);
}, workerTimeout);
return abortable( return abortable(
signal, signal,
this._workerApi![methodName](...args) as any, this._workerApi![methodName](...args) as any,
).finally(() => { ).finally(() => {
done = true; // No longer care about aborting - this task is complete.
clearTimeout(timeoutId); signal.removeEventListener('abort', onAbort);
// Start a timer to clear up the worker.
this._workerTimeout = setTimeout(() => {
this._terminateWorker();
}, workerTimeout);
}); });
}); });
return this._queue;
} as any; } as any;
} }