method

SQL.listen

channel: string,
onnotify: (payload: string) => void,
onlisten?: () => void
): Promise<ListenSubscription>;

Subscribe to a PostgreSQL LISTEN channel. Resolves once the server has acknowledged the subscription, with a handle that removes it again.

Every call is its own registration: several on one channel share a single server-side subscription and each receives every notification. All of them share one dedicated connection, opened by the first listen() and closed when the last registration is removed. If it drops, it is reconnected with exponential backoff and every channel is re-subscribed; onlisten runs again each time.

A throwing onnotify or onlisten is reported as an uncaught exception.

@param channel

Channel name, quoted for you; at most 63 bytes, the PostgreSQL identifier limit

@param onnotify

Receives each notification's payload

@param onlisten

Runs once the LISTEN is acknowledged, initially and after every reconnect

const subscription = await sql.listen("events", payload => console.log(payload));
await sql.notify("events", "hello");
await subscription.unlisten();

Referenced types

interface ListenSubscription

One registration made by SQL.listen.

  • readonly channel: string
  • [Symbol.asyncDispose](): PromiseLike<void>;
  • unlisten(): Promise<void>;

    Remove this registration. Resolves once the channel is no longer subscribed, or immediately when other registrations on it remain. Idempotent; await using calls it at the end of the scope.