Waiting on fetch() in Kotlin JS?

Viewed 1321

I'm writing a WebGL app in Kotlin JS, and as such I need to fetch resource such as .obj files and shaders. I want to do this through HTTP requests, but I've run into issues.

I'm currently trying to do this via JS's fetch() API. The problem is that this is obviously asynchronous, and fetching the resources needs to be done before the render loop can start (i.e. fetching the resources is initialisation).

I'm really struggling to get this to work synchronously. That is, my program should not continue onto loading buffers and the main draw loop before it has fetched the shaders and .obj files. How can I get this to work in Kotlin JS? Is fetch() not the right way to do this?

2 Answers

I'm not sure about fetch() but Ktor comes with a multiplatform HTTP library which you can use out of the box. You can find it here.

And example of such call looks like this:

suspend fun sequentialRequests() {
    val client = HttpClient()

    // Get the content of an URL.
    val firstBytes = client.get<ByteArray>("https://127.0.0.1:8080/a")

    // Once the previous request is done, get the content of an URL.
    val secondBytes = client.get<ByteArray>("https://127.0.0.1:8080/b")

    client.close()
}

If you want to use fetch, you can do something like this.

import kotlinx.browser.window
import kotlinx.coroutines.*
import kotlin.js.Promise

    suspend fun main() {
        val promise = Promise.resolve(window.fetch("https://jsonplaceholder.typicode.com/todos/1").then {response->
            response.json()
        }.then {
            it
        }).await()
    
        console.log(JSON.stringify(promise))}

There are definitely other options. Let me know if this doesn't do it for you.

Good luck!

Related