Skip to main content

.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
Function called once when data is available.Signature: function(data, key)
  • data - The data at this node
  • key - The property key
object
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):
The .once() method:
  1. Subscribes to data using .get()
  2. Waits for data to arrive or timeout
  3. Calls the callback with the data
  4. Automatically unsubscribes with .off()
  5. Cleans up internal references

Performance Considerations

Wait Timeout

The default wait time (99ms) determines when GUN assumes data doesn’t exist:

Differences from .on()

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 undefined for non-existent data after the wait timeout