Sub topic 9
Cancelling Registrations with Unregister Tokens
This chapter assumes you already know how to create a FinalizationRegistry, call register(), and pass a held value to the cleanup callback. Here you will learn how to cancel a registration once the callback is no longer needed.
Why Cancel a Registration?
Finalization is often a fallback. Say an object wraps an external resource, such as a file handle. The normal path is for the caller to close it explicitly. The registry callback exists only for the case where the caller forgets. If the caller does close the resource, the callback should not run later and close it a second time. An unregister token lets you remove the registration so this cannot happen.
The Third Argument to register()
register() takes an optional third argument:
registry.register(target, heldValue, unregisterToken);The unregister token is a key that identifies one or more registrations. Later, registry.unregister(token) removes every registration made with that token. If you leave the token out, you cannot cancel that registration.
Token rules:
| Rule | Detail |
|---|---|
| Allowed types | Objects and non-registered symbols, the same values that are valid weak targets |
| Held strength | The registry holds the token weakly, so the token does not keep anything alive |
| Sharing | One token can cover many registrations, and one call removes all of them |
| Invalid token | `register()` and `unregister()` throw a `TypeError` for primitives such as strings |
| Return value | `unregister()` returns `true` if it removed at least one registration, otherwise `false` |
The most common choice of token is the target itself. Because the token is held weakly, using the target as the token does not keep it alive. The held value is different: it cannot be the target.
A Worked Example
The wrapper below registers itself as both the target and the token. The inner handle is the held value. Calling close() cancels the fallback before it closes the handle.
const registry = new FinalizationRegistry((fileHandle) => {
console.warn('Handle was not closed explicitly; closing now');
fileHandle.close();
});
class Wrapper {
constructor(fileHandle) {
this.fileHandle = fileHandle;
registry.register(this, fileHandle, this);
}
close() {
const removed = registry.unregister(this);
console.log(`Registration removed: ${removed}`);
this.fileHandle.close();
}
}
const fakeHandle = { close: () => console.log('handle closed') };
const w = new Wrapper(fakeHandle);
w.close(); // Registration removed: true, then: handle closed
w.close(); // Registration removed: false, then: handle closedThe second close() call returns false because nothing is left to remove. In real code you would guard against closing the handle twice, for example with a closed flag.
Common Errors
- Forgetting the token. If you write
register(this, fileHandle), there is nothing to pass tounregister(), and the fallback can still fire after an explicit close. - Using a string token.
registry.unregister('file-1')throws aTypeError. Use an object or a non-registered symbol. - Expecting unregister to stop a callback already in progress.
unregister()removes pending registrations. It cannot undo a callback the engine has already scheduled or run, so make cleanup safe to run more than once.
Exercise
You call registry.register(obj, 'id-7') and later call registry.unregister(obj). What does unregister return, and why?
Show answer
It returns false. The registration was made without an unregister token, so no registration is associated with obj as a token. obj was only the target, and a target does not act as a token unless you pass it as the third argument.
Exercise
Why is it safe to use the target itself as the unregister token, when using the target as the held value throws a TypeError?
Show answer
The registry holds unregister tokens weakly, so the token does not keep the target alive. Held values are held strongly, so a held value equal to the target would keep the target reachable forever, and register() rejects it.