我在下面有這個示例代碼。我不想阻止里面的組合器resource.map,所以我把Await.result里面Future。但是當我測驗這個異步遞回時,我concurrent.TimeoutException從myRes. 代碼有什么問題?我如何解決它?謝謝你。
// Code start here
val responses = Future.sequence(resource.map(params => asyncRecursionFunc(params)))
Await.result(responses, 5.minutes)
// My async function
def asyncRecursionFunc(params: sampleParameters, maxTryTimes: Int = 2, awaitTime: Int = 1): Future[(Seq[sample], String)] = {
val res: Future[GraphQLCluent.GraphQLResponse[SearchQueryResponse]] = client.query("gql", params).result
Future {
val myRes: GraphQLCluent.GraphQLResponse[SearchQueryResponse] = Await.result(res, 2.minutes)
val myValue: Seq[sample] = myRes.right.toSeq.flatmap(res => res)
if( !myValue.isEmpty || maxTryTimes <= 0 ){
(myValue, "stringMessage")
}
else{
Await.result(asyncRecursionFunc(params, maxTryTimes - 1, awaitTime 1), (2*(awaitTime 1)).minutes)
}
}
}
uj5u.com熱心網友回復:
是的,你應該使用flatMap.
即使在 a 內部Await也很糟糕Future(在某種程度上,它實際上更糟)。這也可能是導致您立即出現問題的原因(前幾個查詢耗盡了池中的所有執行緒,然后Await永遠阻塞)。
嘗試以真正異步的方式進行:
def doQuery(params: Foo, maxTries: Int) = client.query("gql", params).result.flatMap {
case Right(r) if r.nonEmpty => Future.successful(r -> "stringmessage")
case _ if maxTries == 1 => Future.successful(Nil -> "stringmessage")
case _ => doQuery(params, maxTries-1)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/512157.html
標籤:斯卡拉异步递归异步等待
