diff --git a/src/lib/SinglePromise.hx b/src/lib/SinglePromise.hx new file mode 100644 index 0000000..9b92a32 --- /dev/null +++ b/src/lib/SinglePromise.hx @@ -0,0 +1,48 @@ +package lib; + +using tink.CoreApi; + +class SinglePromise { + private var inProgress:Bool = false; + private var interalPromise:Promise = null; + private var interalResolve:T->Void = null; + private var interalReject:(Error->Void) = null; + private final activate:Void->Void; + + public function new(activate:Void->Void) { + this.activate = activate; + } + + public function request():Promise { + if (this.inProgress) { + return this.interalPromise; + } + + this.inProgress = true; + + this.interalPromise = new Promise((resolve, reject) -> { + this.interalResolve = resolve; + this.interalReject = reject; + + this.activate(); + + return null; + }); + + return this.interalPromise; + } + + public function resolve(val:T) { + if (this.inProgress) { + this.interalResolve(val); + this.inProgress = false; + } + } + + public function reject(err:Error) { + if (this.inProgress) { + this.interalReject(err); + this.inProgress = false; + } + } +} diff --git a/src/lib/SingleTimeoutPromise.hx b/src/lib/SingleTimeoutPromise.hx new file mode 100644 index 0000000..d7c4442 --- /dev/null +++ b/src/lib/SingleTimeoutPromise.hx @@ -0,0 +1,60 @@ +package lib; + +import kernel.Timer; + +using tink.CoreApi; + +class SingleTimeoutPromise { + private var inProgress:Bool = false; + private var interalPromise:Promise = null; + private var interalResolve:T->Void = null; + private var interalReject:(Error->Void) = null; + private var timer:Timer = null; + + private final activate:Void->Void; + private final timeout:Int; + + public function new(timeout:Int, activate:Void->Void) { + this.activate = activate; + this.timeout = timeout; + } + + public function request():Promise { + if (this.inProgress) { + return this.interalPromise; + } + + this.inProgress = true; + + this.interalPromise = new Promise((resolve, reject) -> { + this.interalResolve = resolve; + this.interalReject = reject; + + this.activate(); + + this.timer = new Timer(this.timeout, () -> { + this.reject(new Error("Timeout")); + }); + + return null; + }); + + return this.interalPromise; + } + + public function resolve(val:T) { + if (this.inProgress) { + this.interalResolve(val); + this.inProgress = false; + this.timer.cancle(); + } + } + + public function reject(err:Error) { + if (this.inProgress) { + this.interalReject(err); + this.inProgress = false; + this.timer.cancle(); + } + } +}