MCPcopy Create free account
hub / github.com/angular/angular / PendingTasks

Class PendingTasks

packages/core/src/pending_tasks.ts:43–102  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

41 * @publicApi 20.0
42 */
43export class PendingTasks {
44 private readonly internalPendingTasks = inject(PendingTasksInternal);
45 private readonly scheduler = inject(ChangeDetectionScheduler);
46 private readonly errorHandler = inject(INTERNAL_APPLICATION_ERROR_HANDLER);
47 private readonly destroyRef = inject(DestroyRef);
48 /**
49 * Adds a new task that should block application's stability.
50 * @returns A cleanup function that removes a task when called.
51 */
52 add(): () => void {
53 const taskId = this.internalPendingTasks.add();
54 return () => {
55 if (!this.internalPendingTasks.has(taskId)) {
56 // This pending task has already been cleared.
57 return;
58 }
59 // Notifying the scheduler will hold application stability open until the next tick.
60 this.scheduler.notify(NotificationSource.PendingTaskRemoved);
61 this.internalPendingTasks.remove(taskId);
62 };
63 }
64
65 /**
66 * Runs an asynchronous function and blocks the application's stability until the function completes.
67 *
68 * ```ts
69 * pendingTasks.run(async () => {
70 * const userData = await fetch('/api/user');
71 * this.userData.set(userData);
72 * });
73 * ```
74 *
75 * @param fn The asynchronous function to execute
76 * @developerPreview 19.0
77 */
78 run(fn: () => Promise<unknown>): void {
79 const removeTask = this.add();
80 try {
81 fn()
82 .catch((err) => {
83 if (!this.destroyRef.destroyed) {
84 this.errorHandler(err);
85 }
86 })
87 .finally(removeTask);
88 } catch (err) {
89 if (!this.destroyRef.destroyed) {
90 this.errorHandler(err);
91 }
92 removeTask();
93 }
94 }
95
96 /** @nocollapse */
97 static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
98 token: PendingTasks,
99 providedIn: 'root',
100 factory: () => new PendingTasks(),

Callers

nothing calls this directly

Calls 2

injectFunction · 0.90
ɵɵdefineInjectableFunction · 0.90

Tested by

no test coverage detected