Issue
I got this error when trying to transform gapi calls into Promises, but I suppose calls to other functions may result in the same issue. First, I added the library as a script in the page:
script(src = "https://apis.google.com/js/platform.js") {
async = true
defer = true
}
next, I fetched gapi object from window:
import kotlinx.browser.window
import org.w3c.dom.get
val gapi = window["gapi"]
finally, I used the load function like so:
import kotlin.js.Promise
fun loadGapi() = Promise<Unit> { resolve, _ ->
gapi.load("client:auth2") { resolve(Unit) }
}
giving me a warning in the IDE:
This resulted in the following error when called inside a page:
Uncaught (in promise) ClassCastException {message: undefined, cause: undefined, name: 'ClassCastException', stack: 'ClassCastException\n at THROW_CCE (http://localh… (http://localhost:3000/static/app.js:4930:14)'}
Solution
Not sure why this happens. I tried reproducing the issue with evaluated JS code to no avail:
import kotlin.js.Promise
fun loadGapi(): Promise<Any> {
val functionReturningUndefined =
js("function (resolve) { resolve('test'); return undefined; }")
return Promise { resolve, _ ->
functionReturningUndefined { param -> resolve(param as Any) } as Unit
}
}
Anyways, the problem can be resolved by ignoring the return value of the function and adding return@Promise Unit like so:
fun loadGapi() = Promise<Unit> { resolve, _ ->
gapi.load("client:auth2") { resolve(Unit) }
return@Promise Unit
}
Alternatively, an extension function may be added (I put mine in shared/Promises.kt) that specifically targets the dynamic return type:
fun <T> Promise(executor: (resolve: (T) -> Unit, reject: (Throwable) -> Unit) -> dynamic) =
Promise<T> { resolve, reject ->
executor(resolve, reject)
Unit
}
then simply:
import shared.Promise
fun loadGapi() = Promise<Unit> { resolve, _ ->
gapi.load("client:auth2") { resolve(Unit) }
}
Answered By - Jezor

0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.