added SinglePromise and SingleTimeoutPromise

This commit is contained in:
Niklas Kapelle 2024-10-16 23:42:21 +02:00
parent afbd1dfd68
commit af6a4c840b
Signed by: niklas
GPG Key ID: 4EB651B36D841D16
2 changed files with 108 additions and 0 deletions

48
src/lib/SinglePromise.hx Normal file
View File

@ -0,0 +1,48 @@
package lib;
using tink.CoreApi;
class SinglePromise<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 final activate:Void->Void;
public function new(activate:Void->Void) {
this.activate = activate;
}
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();
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;
}
}
}

View File

@ -0,0 +1,60 @@
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 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();
}
}
}