.once()
The.once() method reads data from the graph once and calls the callback. Unlike .on(), it automatically unsubscribes after receiving data, making it ideal for one-time reads.
Signature
Parameters
Function called once when data is available.Signature:
function(data, key)data- The data at this nodekey- The property key
Options for read behavior
Return Value
Returns the same GUN chain reference for method chaining.Examples
Basic Read
Async/Await Pattern
Handle Missing Data
Chain Multiple Reads
Custom Wait Time
Read from Collection
Conditional Reading
Implementation Details
From the source code (on.js:57-85):.once() method:
- Subscribes to data using
.get() - Waits for data to arrive or timeout
- Calls the callback with the data
- Automatically unsubscribes with
.off() - Cleans up internal references
Behavior with Links
Performance Considerations
Wait Timeout
The default wait time (99ms) determines when GUN assumes data doesn’t exist:Differences from .on()
| Feature | .once() | .on() |
|---|---|---|
| Triggers | One time only | Every update |
| Unsubscribe | Automatic | Manual with .off() |
| Use case | Read current value | Realtime sync |
| Performance | Cleans up automatically | Stays in memory |
| Memory | Low (auto cleanup) | Can leak if not unsubscribed |
Notes
.once()is perfect for reading data without setting up a subscription- It automatically cleans up, preventing memory leaks
- For realtime updates, use
.on()instead - The callback might not fire if data doesn’t exist and timeout expires
- Links are automatically resolved to their target data
- The callback receives
undefinedfor non-existent data after the wait timeout