Sub topic 10
PendingTasks and Application Stability
This chapter assumes you can build standalone components, use signals, and write Promise-based async code. You should also know how zoneless mode is enabled (the previous chapters covered this). Here you will learn how Angular decides the application is "stable" without Zone.js, and how to tell it about work it cannot see.
What "stable" means
Angular exposes a notion of application stability: the app has no outstanding work that could still change what is rendered. Several features wait for this moment:
- Server-side rendering (SSR) serializes the HTML only after the app becomes stable.
- Prerendering at build time does the same.
- Tests call
fixture.whenStable()andApplicationRef.whenStable()to wait for it. - Hydration and some router behavior depend on it.
In a zone-based app, Zone.js answered the question automatically. It patched setTimeout, Promise, fetch, XMLHttpRequest and event listeners, so NgZone knew when any macrotask or microtask was still pending. NgZone.isStable turned true when the queue emptied.
Without Zone.js, Angular cannot see arbitrary async work. A fetch call is invisible to it. Stability is instead computed from two things Angular does know about:
- Work registered through
PendingTasks. - Whether a change detection run is scheduled or in progress.
Angular's own APIs, such as HttpClient and the router, register their work with PendingTasks internally. Your own async code does not, unless you add it.
Ignore the empty fence above. The real diagram follows.
The problem: invisible work
Consider a service that loads data with fetch. In a zone-based app, SSR waits for that request because Zone.js tracks it. In a zoneless app, the server may serialize the page before the response arrives. The HTML then contains the loading state, and the client has to fetch the data again.
Tests have the same problem. await fixture.whenStable() can resolve while your fetch is still in flight, and the assertion that follows fails or passes by accident.
The fix is to register the work.
Registering work with PendingTasks.run()
PendingTasks is an injectable service in @angular/core. The simplest method is run(). It takes an async function, increments the pending count, calls the function, and decrements the count when the returned Promise settles, whether it resolves or rejects. It returns the function's result.
import { Injectable, inject, PendingTasks } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class DataLoader {
private readonly pendingTasks = inject(PendingTasks);
load(url: string) {
return this.pendingTasks.run(async () => {
const response = await fetch(url);
return response.json();
});
}
}While load() is running, the app is unstable. SSR and whenStable() wait. Callers still get the parsed JSON, because run() passes the value through.
What counts as a good candidate
Wrap work that:
- Must finish before the server sends HTML (initial data, config, translations).
- Tests need to wait for.
- Is started by your code and not by an Angular API that already tracks it.
Do not wrap work that never ends or runs indefinitely, such as a WebSocket message loop or a polling setInterval. A task that never completes keeps the app unstable forever. On the server, that means a request that hangs until a timeout.
Manual control with add()
When the work is not a single async function, for example an event-based callback, use add(). It returns a function you call to mark the task as finished.
import { Injectable, inject, PendingTasks } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class LegacyUploader {
private readonly pendingTasks = inject(PendingTasks);
upload(file: File, onDone: (result: string) => void): void {
const removeTask = this.pendingTasks.add();
const reader = new FileReader();
reader.onload = () => {
try {
onDone(String(reader.result));
} finally {
removeTask();
}
};
reader.onerror = () => removeTask();
reader.readAsText(file);
}
}Every code path must call removeTask(). A path that throws before the call, or an error event you forgot to handle, leaves the task open and the app unstable. Use try/finally as above. Prefer run() whenever the work can be expressed as a Promise, because it cleans up for you.
| Method | Use it when | Who ends the task |
|---|---|---|
| `run(fn)` | Work is a Promise-returning function | Angular, when the Promise settles |
| `add()` | Work is callback or event based | You, by calling the returned function |
Tasks and change detection
Pending tasks do not trigger change detection. They only report that work is outstanding. Rendering still depends on the normal triggers: signal changes, markForCheck(), the async pipe, template events, and so on.
This matters in one case. If load() resolves and you write the result into a plain field, the task ends but the view is not refreshed. Store results in a signal.
import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
import { DataLoader } from './data-loader';
@Component({
selector: 'app-profile',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
@if (profile(); as p) {
<h2>{{ p.name }}</h2>
} @else {
<p>Loading…</p>
}
`,
})
export class Profile {
private readonly loader = inject(DataLoader);
protected readonly profile = signal<{ name: string } | null>(null);
constructor() {
this.loader.load('/api/profile').then((data) => this.profile.set(data));
}
}The task keeps the server waiting, and the signal write schedules the render. The server therefore sees the final HTML.
Waiting for stability
ApplicationRef.whenStable() returns a Promise that resolves when the app is stable. This is useful in bootstrap scripts and custom server code.
import { ApplicationRef, inject } from '@angular/core';
export async function waitUntilSettled(): Promise<void> {
const appRef = inject(ApplicationRef);
await appRef.whenStable();
}Call it from an injection context, such as a factory or runInInjectionContext. For tests, fixture.whenStable() is the usual choice. The next chapter group shows it in full.
Common errors
- Forgetting to wrap custom async work. Symptom: SSR output shows loading states, or a test asserts before data arrives. Fix: wrap with
run(). - Leaking a task with
add(). Symptom: SSR requests time out, orwhenStable()never resolves. Fix:try/finally, or switch torun(). - Wrapping infinite work. Symptom: the app is never stable. Fix: wrap only the part that has an end, such as the first message.
- Expecting
run()to refresh the view. Symptom: the task finishes but the screen is stale. Fix: write results to a signal or callmarkForCheck(). - Awaiting
whenStable()inside work that is itself pending. Symptom: deadlock, because the task waits for stability and stability waits for the task. Fix: await stability from outside the tracked function.
Exercises
Exercise
A zoneless component fetches data with fetch() in a service, and the server-rendered HTML shows "Loading…" even though the request succeeds. What is the likely cause, and what is the smallest fix?
Show answer
Angular cannot see the fetch call without Zone.js, so the app reports stable before the response arrives and SSR serializes early. Wrap the request in PendingTasks.run(), so the app stays unstable until the Promise settles. Also make sure the result is stored in a signal so the view updates.
Exercise
You use const done = pendingTasks.add(); around a callback-based API. The server hangs on some requests. What should you check, and how do you make the code safe?
Show answer
Check whether done() is skipped when the callback throws or when an error event fires. Call done() in a finally block and in every error handler. If the work can be a Promise, use run(), which ends the task on both resolve and reject.
Exercise
Does ending a pending task cause the component to re-render? Explain.
Show answer
No. Pending tasks only affect the stability signal. Re-rendering needs a change detection trigger such as a signal write, markForCheck(), or an async pipe emission.