kotlin - How to rewrite the code to use Kotlin's kotlinx-coroutines-jdk8?
问题描述
How to rewrite this code using Kotlin jdk async functions to avoid the error "Suspension functions can be called only within coroutine body"?
var result: CompletableFuture<CarInfoDto>? = null
try {
result = CompletableFuture.supplyAsync {
runBlocking {
myService.getCarInfo(carId) //**"Suspension functions can be called only within coroutine body"**
}
}
return ResponseEntity(future?.get(1000, TimeUnit.MILLISECONDS), HttpStatus.OK)
} catch (timeoutException: TimeoutException) {
解决方案
当前代码中的get()
调用阻止当前线程等待异步作业,因此首先启动此异步作业没有任何好处,您可以简单地调用runBlocking
(withTimeout
如果您真的对超时感兴趣,可以使用):
try {
val result = runBlocking {
withTimeout(1000) {
myService.getCarInfo(carId)
}
}
return ResponseEntity(result, HttpStatus.OK)
} catch (timeoutException: TimeoutException) {
...
}
但是,由于您似乎在使用 Spring,您应该能够使您的控制器功能成为一个suspend
函数,并且您可能根本不需要创建新的协程或块(只需调用您的getCarInfo()
方法)。
推荐阅读
- c++ - 如何在虚拟机上使用 Visual Studio 设置内核调试器
- c++ - 在 C++ 中绘制 Windows 10 壁纸
- azure - azure-arm winrm 使用打包程序超时错误
- python - Context Locals 和 The Request Context 如何协同工作?
- google-sheets - 如何发布谷歌表格插件
- java - 在 Java Spring 中使用需要带有 @Formula 注释的选项的 sql 函数
- java - 无法使用 Java 11 升级构建我的项目
- c# - PointerEnter 事件不会触发悬停状态
- javascript - 如何在 Adobe Indesign 的扩展脚本中定义换行符
- python - 处理 aiohttp 中的错误请求