@@ -23,19 +23,15 @@ export function selectRandomPeer(peers: Peer[]): Peer | undefined {
23
23
* @returns The peer with the lowest latency, or undefined if no peer could be reached
24
24
*/
25
25
export async function selectLowestLatencyPeer (
26
- getPing : ( peerId : PeerId ) => Promise < number > ,
26
+ peerPings : Map < string , number > ,
27
27
peers : Peer [ ]
28
28
) : Promise < Peer | undefined > {
29
29
if ( peers . length === 0 ) return ;
30
30
31
31
const results = await Promise . all (
32
- peers . map ( async ( peer ) => {
33
- try {
34
- const ping = await getPing ( peer . id ) ;
35
- return { peer, ping } ;
36
- } catch ( error ) {
37
- return { peer, ping : Infinity } ;
38
- }
32
+ peers . map ( ( peer ) => {
33
+ const ping = peerPings . get ( peer . id . toString ( ) ) ?? Infinity ;
34
+ return { peer, ping } ;
39
35
} )
40
36
) ;
41
37
@@ -73,7 +69,7 @@ export async function getPeersForProtocol(
73
69
*/
74
70
export async function selectPeerForProtocol (
75
71
peerStore : PeerStore ,
76
- getPing : ( peerId : PeerId ) => Promise < number > ,
72
+ peerPings : Map < string , number > ,
77
73
protocols : string [ ] ,
78
74
peerId ?: PeerId
79
75
) : Promise < { peer : Peer ; protocol : string } > {
@@ -87,7 +83,7 @@ export async function selectPeerForProtocol(
87
83
}
88
84
} else {
89
85
const peers = await getPeersForProtocol ( peerStore , protocols ) ;
90
- peer = await selectLowestLatencyPeer ( getPing , peers ) ;
86
+ peer = await selectLowestLatencyPeer ( peerPings , peers ) ;
91
87
if ( ! peer ) {
92
88
peer = selectRandomPeer ( peers ) ;
93
89
if ( ! peer )
0 commit comments