From 9ee58bd6c72f6893b41be0f40e84c1c6fd167576 Mon Sep 17 00:00:00 2001 From: fiatjaf Date: Tue, 4 Apr 2023 10:23:26 -0300 Subject: [PATCH] fix async race condition that caused pool.publish() callbacks to not be called. fixes https://github.com/nbd-wtf/nostr-tools/issues/169 --- pool.ts | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/pool.ts b/pool.ts index f59100b..f6ea3f6 100644 --- a/pool.ts +++ b/pool.ts @@ -159,22 +159,36 @@ export class SimplePool { } publish(relays: string[], event: Event): Pub { - const pubs: Pub[] = [] - relays.forEach(async relay => { + const pubPromises: Promise[] = relays.map(async relay => { let r try { r = await this.ensureRelay(relay) - pubs.push(r.publish(event)) - } catch (_) {} + return r.publish(event) + } catch (_) { + return {on() {}, off() {}} + } }) + + const callbackMap = new Map() + return { on(type, cb) { - pubs.forEach((pub, i) => { - pub.on(type, () => cb(relays[i])) + relays.forEach(async (relay, i) => { + let pub = await pubPromises[i] + let callback = () => cb(relay) + callbackMap.set(cb, callback) + pub.on(type, callback) }) }, - off() { - // do nothing here, FIXME + + off(type, cb) { + relays.forEach(async (_, i) => { + let callback = callbackMap.get(cb) + if (callback) { + let pub = await pubPromises[i] + pub.off(type, callback) + } + }) } } }