返回名称不以异步结尾的Deferred函数

时间:2019-01-30 16:26:45

标签: kotlin kotlinx.coroutines

我最近尝试学习Kotlin协程,我注意到在返回async的映射的情况下,IDE会显示消息,提示Function returning Deferred with a name that does not end with async。这是我的代码

runBlocking {
    try {
        val siteDeferred = async { getSite(order) }
        // Place where I get warning-----------| (Function returning Deferred with a name that does not end with Async)
        //                                     v
        val orderLineDeferred = order.line.map { async { getOrderDetail(it) } }

        // Place where I get warning-------------------| (Function returning Deferred with a name that does not end with Async)
        //                                             v
        val orderLineProductsDeferred = order.line.map { async { getOrderProductInformation(it.productId) } }

        val site = siteDeferred.await()
        val orderLine = orderLineDeferred.awaitAll()
        val orderLineProducts = orderLineProductsDeferred.awaitAll()
    } catch (e: Throwable) {
        throw Exception(e.message)
    }
}

private suspend getOrderDetail(OrderLine orderLine): OrderDetail...
private suspend getSite(Order order): Site ...
private suspend getOrderProductInformation(String productId): Product ...

我在这里错过了什么吗?此外,我想知道这是否是进行异常处理的正确方法,是否有办法清除try块,以便即使可以使用也可以直接获取值,即使我必须使用async在其他方法中。

1 个答案:

答案 0 :(得分:1)

函数 getSite()重命名为 getSiteAsync(),其他函数都以这种方式修改。