Edoardo Luppi
06/24/2023, 1:45 PMPromise
or CompletableFuture
, depending on the platform.
Can I, at compile time, generate an additional method for each target (JS/JVM) to expose the private promise/future? Maybe with KSP?
This would allow doing something like the following, in TS context:
const result = await mySocket.connect(...).promise()
franztesca
06/24/2023, 2:17 PMEdoardo Luppi
06/24/2023, 2:21 PMinterface
ZPromise // interface - commonMain
- JsZPromise // class - jsMain
- JvmZPromise // class - jvmMain
Edoardo Luppi
06/24/2023, 2:22 PMpromise
field public or add a method to expose it, it won't get built in the TS types declaration fileEdoardo Luppi
06/24/2023, 2:25 PMexport declare namespace my.namespace {
function promise<T>(_this_: my.namespace.JsZPromise<T>): Promise<T>;
}
Edoardo Luppi
06/24/2023, 2:39 PMexpect interface
, and in the actual interface for JS I've added a
fun promise(): Promise<T>
method. What a mental tripEdoardo Luppi
06/24/2023, 2:40 PMexpect interface
? I mean why is the above allowed? It's veeery strangeEdoardo Luppi
06/24/2023, 2:41 PMexpect interface ZPromise<T> {
fun <S> then(thenFn: (T) -> S): ZPromise<S>
fun <S> thenDeferred(thenFn: (T) -> ZPromise<S>): ZPromise<S>
fun <S> catch(catchFn: (Throwable) -> S): ZPromise<S>
fun <S> catchDeferred(catchFn: (Throwable) -> ZPromise<S>): ZPromise<S>
fun finally(thenFn: (T?, Throwable?) -> Unit)
}
An in JS
@JsExport
actual interface ZPromise<T> {
fun promise(): Promise<T>
actual fun <S> then(thenFn: (T) -> S): ZPromise<S>
actual fun <S> thenDeferred(thenFn: (T) -> ZPromise<S>): ZPromise<S>
actual fun <S> catch(catchFn: (Throwable) -> S): ZPromise<S>
actual fun <S> catchDeferred(catchFn: (Throwable) -> ZPromise<S>): ZPromise<S>
actual fun finally(thenFn: (T?, Throwable?) -> Unit)
}
turansky
06/24/2023, 4:05 PMEdoardo Luppi
06/24/2023, 4:05 PMexpect/actual interface
, it seems very weird to use itAhmed na
06/25/2023, 3:32 AMpromise
instead of having it with the object it self (not ideal I know)
so in jsMain
extend your class
fun <ResultT> YourClass<ResultT>.promise(): Promise<ResultT> {
return Promise { success: (ResultT) -> Unit, failure: (Throwable) -> Unit ->
onSuccess {
success(it)
}.onFailure {
failure(it)
}
}
}
And your implementation would be like
const result = await YourClass.promise(mySocket.connect(...))
It's not ideal but still reusable and readable
Example
Usageturansky
06/25/2023, 5:00 AMPromiseLike
Edoardo Luppi
06/25/2023, 9:25 AM