diff --git a/src/lease.ts b/src/lease.ts index 2bbe38c..975b3e9 100644 --- a/src/lease.ts +++ b/src/lease.ts @@ -244,7 +244,7 @@ export class Lease extends EventEmitter { // far past the end of our key's TTL, there's no way we're going to be // able to renew it. Fire a "lost". if (Date.now() - this.lastKeepAlive > 2 * 1000 * this.ttl) { - this.emit('lost', new GRPCConnectFailedError('We lost connect to etcd and our lease has expired.')); + this.emit('lost', new GRPCConnectFailedError('We lost connection to etcd and our lease has expired.')); return this.close(); } diff --git a/src/util.ts b/src/util.ts index 24a6447..80bb2f8 100644 --- a/src/util.ts +++ b/src/util.ts @@ -157,13 +157,23 @@ export function forOwn(obj: T, iterator: (value: T[K], key * fire on the emitter. */ export function onceEvent(emitter: EventEmitter, ...events: string[]): Promise { - return new Promise(resolve => { - const handler = (data: any) => { - events.forEach(name => emitter.removeListener(name, handler)); - resolve(data); + return new Promise((resolve, reject) => { + const teardown: (() => void)[] = []; + + const handler = (data: any, event: string) => { + teardown.forEach(t => t()); + if (event === 'error') { + reject(data); + } else { + resolve(data); + } }; - events.forEach(event => emitter.once(event, handler)); + events.forEach(event => { + const fn = (data: any) => handler(data, event); + teardown.push(() => emitter.removeListener(event, fn)); + emitter.once(event, fn); + }); }); } diff --git a/src/watch.ts b/src/watch.ts index 84b0847..1c471b8 100644 --- a/src/watch.ts +++ b/src/watch.ts @@ -321,13 +321,7 @@ export class WatchBuilder { this.namespace.applyToRequest(this.request), ); - return onceEvent(watcher, 'connected', 'error').then(res => { - if (res instanceof Error) { - throw res; - } - - return watcher; - }); + return onceEvent(watcher, 'connected').then(() => watcher); } }