Skip to content
This repository was archived by the owner on Feb 2, 2021. It is now read-only.

Add event emitter helper method #940

Merged
merged 2 commits into from
Apr 11, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as net from "net";
let Table = require("cli-table");
import { platform, EOL } from "os";
import { ReadStream } from "tty";
import { EventEmitter } from "events";

export function deferPromise<T>(): IDeferPromise<T> {
let resolve: (value?: T | PromiseLike<T>) => void;
Expand Down Expand Up @@ -337,6 +338,16 @@ export function isPromise(candidateFuture: any): boolean {
return !!(candidateFuture && typeof (candidateFuture.then) === "function");
}

export async function attachAwaitDetach(eventName: string, eventEmitter: EventEmitter, eventHandler: Function, operation: Promise<any>) {
eventEmitter.on(eventName, eventHandler);

try {
await operation;
} finally {
eventEmitter.removeListener(eventName, eventHandler);
}
}

export async function connectEventually(factory: () => Promise<net.Socket>, handler: (_socket: net.Socket) => void): Promise<void> {
async function tryConnect() {
let tryConnectAfterTimeout = setTimeout.bind(undefined, tryConnect, 1000);
Expand Down