I dont think i am using coroutines correctly here

i want to be able to reuse this call to my server from a JS backend:

     suspend fun customerSummaryTwo(req: GenericIntEQ)  : Deferred<CustomerPDSummaryDTO> {
        val deffered: Deferred<CustomerPDSummaryDTO> = GlobalScope.async{jsonClient.post<CustomerPDSummaryDTO>("http://localhost:8080/customerSummary"){
            contentType(ContentType.Application.Json)
            body = req
        }}
        return deffered
    }

and i am calling like this

attrs.onClickFunction = { evt ->
    GlobalScope.launch {
        val _req = GenericIntEQ(theInt = it.id)
        val firstRequest = PredictService.customerSummaryTwo(_req)
        val result = firstRequest.await()
        console.log("attrs.onClickFunction four", result)
    }
}

I think i am doing something wrong because i am using GlobalScope twice…

You are right, it seems weird. The main point of suspend functions is to perform synchronous non-blocking operations. Making suspend function asynchronous (as you did) is usually a mistake.

What about this?

suspend fun customerSummaryTwo(req: GenericIntEQ)  : CustomerPDSummaryDTO {
    return jsonClient.post<CustomerPDSummaryDTO>("http://localhost:8080/customerSummary"){
        contentType(ContentType.Application.Json)
        body = req
    }
}

And then just:

val result = PredictService.customerSummaryTwo(_req)

Note that you can do this only if jsonClient.post() is also suspend. I guess it actually is as it looks like Ktor client. If it wouldn’t be suspend, but blocking instead, you would need to wrap this call with withContext(Dispatchers.IO) { }.

1 Like

i will try it…

I was not usable data though. the working code is just what you have suggested with a callback param.

i am new to coroutines, and i am having issues jumping from JVM to JS variant.