65 lines
1.2 KiB
Haxe
65 lines
1.2 KiB
Haxe
package lib;
|
|
|
|
import kernel.Timer;
|
|
|
|
using tink.CoreApi;
|
|
|
|
class SingleTimeoutPromise<T> {
|
|
private var inProgress:Bool = false;
|
|
private var interalPromise:Promise<T> = 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<T> {
|
|
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 isRunning():Bool {
|
|
return this.inProgress;
|
|
}
|
|
|
|
public function resolve(val:T) {
|
|
if (this.inProgress) {
|
|
this.inProgress = false;
|
|
this.timer.cancle();
|
|
this.interalResolve(val);
|
|
}
|
|
}
|
|
|
|
public function reject(err:Error) {
|
|
if (this.inProgress) {
|
|
this.inProgress = false;
|
|
this.timer.cancle();
|
|
this.interalReject(err);
|
|
}
|
|
}
|
|
}
|