(
method: string,
...args: Array<unknown>
)
| 42 | } |
| 43 | |
| 44 | doWork( |
| 45 | method: string, |
| 46 | ...args: Array<unknown> |
| 47 | ): PromiseWithCustomMessage<unknown> { |
| 48 | const customMessageListeners = new Set<OnCustomMessage>(); |
| 49 | |
| 50 | const addCustomMessageListener = (listener: OnCustomMessage) => { |
| 51 | customMessageListeners.add(listener); |
| 52 | return () => { |
| 53 | customMessageListeners.delete(listener); |
| 54 | }; |
| 55 | }; |
| 56 | |
| 57 | const onCustomMessage: OnCustomMessage = message => { |
| 58 | for (const listener of customMessageListeners) listener(message); |
| 59 | }; |
| 60 | |
| 61 | const promise: PromiseWithCustomMessage<unknown> = new Promise( |
| 62 | // Bind args to this function so it won't reference to the parent scope. |
| 63 | // This prevents a memory leak in v8, because otherwise the function will |
| 64 | // retain args for the closure. |
| 65 | (( |
| 66 | args: Array<unknown>, |
| 67 | resolve: (value: unknown) => void, |
| 68 | reject: (reason?: any) => void, |
| 69 | ) => { |
| 70 | const computeWorkerKey = this._computeWorkerKey; |
| 71 | const request: ChildMessage = [CHILD_MESSAGE_CALL, false, method, args]; |
| 72 | |
| 73 | let worker: WorkerInterface | null = null; |
| 74 | let hash: string | null = null; |
| 75 | |
| 76 | if (computeWorkerKey) { |
| 77 | hash = computeWorkerKey.call(this, method, ...args); |
| 78 | worker = hash == null ? null : this._cacheKeys[hash]; |
| 79 | } |
| 80 | |
| 81 | const onStart: OnStart = (worker: WorkerInterface) => { |
| 82 | if (hash != null) { |
| 83 | this._cacheKeys[hash] = worker; |
| 84 | } |
| 85 | }; |
| 86 | |
| 87 | const onEnd: OnEnd = (error: Error | null, result: unknown) => { |
| 88 | customMessageListeners.clear(); |
| 89 | if (error) { |
| 90 | reject(error); |
| 91 | } else { |
| 92 | resolve(result); |
| 93 | } |
| 94 | }; |
| 95 | |
| 96 | const task = {onCustomMessage, onEnd, onStart, request}; |
| 97 | |
| 98 | if (worker) { |
| 99 | this._taskQueue.enqueue(task, worker.getWorkerId()); |
| 100 | this._process(worker.getWorkerId()); |
| 101 | } else { |
no test coverage detected