ktorio / ktor

Framework for quickly creating connected applications in Kotlin with minimal effort
https://ktor.io
Apache License 2.0
12.81k stars 1.04k forks source link

Make ApplicationCall.respondHtml and ApplicationCall.respondHtmlTemplate accept suspendable functions #976

Open sanderploegsma opened 5 years ago

sanderploegsma commented 5 years ago

Ktor Version

1.1.3

Ktor Engine Used(client or server and name)

ktor-server-servlet

JVM Version, Operating System and Relevant Context

1.8, macOS

Feedback

I am working on an application that uses ktor-html-builder combined with asynchronous API calls, and I am having a hard time getting clean and concise code because I am not allowed to .await() within my HTML blocks.

Right now, I am forced to do this:

Routing.routes() {
    get("/") {
        val firstResultDeferred = async { firstCall() }
        val secondResultDeferred = async { secondCall() }

        val firstResult = firstResultDeferred.await()
        val secondResult = secondResultDeferred.await()

        call.respondHtml {
            body {
                p {
                    + "First result: $firstResult"
                }
                p {
                    + "Second result: $secondResult"
                }
            }
        }
    }
}

Instead, I would like to be able to do this:

Routing.routes() {
    get("/") {
        val firstResult = async { firstCall() }
        val secondResult = async { secondCall() }

        call.respondHtml {
            body {
                p {
                    + "First result: ${firstResult.await()}"
                }
                p {
                    + "Second result: ${secondResult.await()}"
                }
            }
        }
    }
}
oleg-larshin commented 4 years ago

Please check the following ticket on YouTrack for follow-ups to this issue. GitHub issues will be closed in the coming weeks.