Retrieve Peer by protocol from `PeerStore`

Using js-libp2p, looking at the PeerStore, ProtoBook, MetadataBook, etc API, it is not straightforward to retrieve a peer that has a given protocol.

Indeed, it seems that the only way to do it is using the peer.Store.getPeers() async generator.

The issue is that if the store has no peers, then the first iteration just hangs and there is no easy way to check whether the peer store has any peers.

export async function hasPeersForProtocol(
  libp2p: Libp2p,
  protocols: string[]
): Promise<boolean> {
  for await (const peer of libp2p.peerStore.getPeers()) {
    let peerFound = false;
    for (let i = 0; i < protocols.length; i++) {
      if (peer.protocols.includes(protocols[i])) {
        peerFound = true;
    if (!peerFound) {
    return true;
  return false;

The only way is is to then use setTimeout so that if a time out is reached then we can assume there is no peer.

Another way would be to use the change:protocols event and just collect the peer at application level.

Is my understanding correct? Or I am missing something obvious? How is the API meant to be used?