MCPcopy
hub / github.com/yume-chan/ya-webadb / TaskQueue

Class TaskQueue

libraries/stream-extra/src/task-queue.ts:4–69  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

2import { isPromiseLike } from "@yume-chan/async";
3
4export class TaskQueue {
5 #ready: PromiseLike<unknown> | undefined;
6 #disposed = false;
7
8 enqueue<T extends MaybePromiseLike<unknown>>(
9 task: () => T,
10 bail?: boolean,
11 ): T;
12 enqueue<T>(task: () => T, bail?: boolean): MaybePromise<T>;
13 enqueue<T>(
14 task: () => MaybePromiseLike<T>,
15 bail = false,
16 ): MaybePromiseLike<T> {
17 if (this.#disposed) {
18 throw new Error("TaskQueue is disposed");
19 }
20
21 if (!this.#ready) {
22 // Init state or all previous tasks are synchronous
23 try {
24 const result = task();
25 if (isPromiseLike(result)) {
26 this.#ready = result.then(
27 () => {},
28 (e) => {
29 if (bail) {
30 throw e;
31 }
32 },
33 );
34 }
35 return result;
36 } catch (e) {
37 if (bail) {
38 // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
39 const promise = Promise.reject(e);
40 // Suppress unhandled-rejection without resolving `#ready`
41 void promise.catch(() => {});
42 this.#ready = promise;
43 }
44 throw e;
45 }
46 }
47
48 const result = this.#ready.then(() => {
49 if (this.#disposed) {
50 throw new Error("TaskQueue is disposed");
51 }
52
53 return task();
54 });
55 this.#ready = result.then(
56 () => {},
57 (e) => {
58 if (bail || this.#disposed) {
59 throw e;
60 }
61 },

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected