How do I import and use an async JS function in Kotlin/JS?

799 views Asked by At

I'm having issues importing a Javascript async function into my Kotlin code.

Here is an example Javascript function :

export async function signUp(email, password){

    console.log("Signing Up");

    try {
        const userCred = await createUserWithEmailAndPassword(auth, email, password);
        console.log(userCred);

        return userCred.user.accessToken
    }
    catch (e) {
        console.log(e);
    }

}

I import it in my Kotlin as such :

@JsModule("@jlengrand/firebase-ports")
@JsNonModule
external object FirebasePorts{

    suspend fun signUp(email: String, password: String) : String
}

When using the function, I expect to get a String out of it :

    var user : String? by mutableStateOf(null)

            Button( attrs = {
                onClick { 
                    GlobalScope.launch {
                        user = FirebasePorts.signUp(email, password)
                    }
                }
            }) {
                Text("Login!")
            }

            // printing the value
            TextArea(value = user.toString())

However, what I get instead is a Promise

enter image description here

What am I doing wrong?

Thanks!

1

There are 1 answers

1
Karel Petranek On BEST ANSWER

Async functions in JS are currently not mapped to suspend functions in Kotlin. To get an async function working in Kotlin, you need to deal with the native promises:

import kotlin.js.Promise

@JsModule("@jlengrand/firebase-ports")
@JsNonModule
external object FirebasePorts {

   fun signUp(email: String, password: String) : Promise<String>
}

Then use FirebasePorts.signUp(...).then { ... } to access the value.