How do I call coroutines from JavaScript?

Calling a suspending function from native Javascript code will be very complicated. It will be easier and more JS-idiomatic to provide a second function that delegates to the first one, but returns a Promise:

fun MyClass.myFuncAsync(): Promise<Unit> = GlobalScope.promise {
    myFunc()
}

Then in your JS, you can call the new function and work with the promise:

const obj = new MyClass()
obj.myFuncAsync().then(function() {
    // code here is executed, when the coroutine finishes
});

Note, that this will work only in browsers, that already support Promises (older browsers don’t support Promises).

If you are on even newer browsers, you can use await keyword on the returned promise:

const obj = new MyClass()
await obj.myFuncAsync()
// code here is executed, when the coroutine finishes

If you need to support browsers that don’t support Promises at all yet, you will need to change the second function to accept a callback instead of returning a Promise:

fun MyClass.myFuncAsync(success: () -> Unit, error: () -> Unit) {
    GlobalScope.launch {
        try {
            myFunc()
            success()
        } catch (e: Throwable) {
            error()
        }
    }
}
4 Likes