KJS: improve declaration for JS Promise and add helpers to simplify some usecases

* add `then` with only one parameter to make usages from Kotlin more idiomatic
* add overload static `resolve` which accepts Promise<S> according to the spec
* add helper functions for `then` to simplify chained usages
  when Promise is returned from `then` or `catch` (workaround for KT-19672)
This commit is contained in:
Zalim Bashorov
2017-10-03 21:46:47 +03:00
parent 30853d5f85
commit beec788bd4
2 changed files with 100 additions and 3 deletions
+23 -3
View File
@@ -16,10 +16,19 @@
package kotlin.js
import kotlin.internal.LowPriorityInOverloadResolution
/**
* Exposes the JavaScript [Promise object](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise) to Kotlin.
*/
public open external class Promise<out T>(executor: (resolve: (T) -> Unit, reject: (Throwable) -> Unit) -> Unit) {
@LowPriorityInOverloadResolution
public open fun <S> then(onFulfilled: ((T) -> S)?): Promise<S>
@LowPriorityInOverloadResolution
public open fun <S> then(onFulfilled: ((T) -> S)?, onRejected: ((Throwable) -> S)?): Promise<S>
public open fun <S> catch(onRejected: (Throwable) -> S): Promise<S>
companion object {
public fun <S> all(promise: Array<out Promise<S>>): Promise<Array<out S>>
@@ -28,9 +37,20 @@ public open external class Promise<out T>(executor: (resolve: (T) -> Unit, rejec
public fun reject(e: Throwable): Promise<Nothing>
public fun <S> resolve(e: S): Promise<S>
public fun <S> resolve(e: Promise<S>): Promise<S>
}
}
public open fun <S> then(onFulfilled: ((T) -> S)?, onRejected: ((Throwable) -> S)? = definedExternally): Promise<S>
// It's workaround for KT-19672 since we can fix it properly until KT-11265 isn't fixed.
inline fun <T, S> Promise<Promise<T>>.then(
noinline onFulfilled: ((T) -> S)?
): Promise<S> {
return this.unsafeCast<Promise<T>>().then(onFulfilled)
}
public open fun <S> catch(onRejected: (Throwable) -> S): Promise<S>
}
inline fun <T, S> Promise<Promise<T>>.then(
noinline onFulfilled: ((T) -> S)?,
noinline onRejected: ((Throwable) -> S)?
): Promise<S> {
return this.unsafeCast<Promise<T>>().then(onFulfilled, onRejected)
}