![](/img/trans.png)
[英]Sequencing Scala Futures with bounded parallelism (without messing around with ExecutorContexts)
[英]Messing with Futures in Scala
我想為REST API制作非阻塞的Web服務。
該Web服務應返回如下所示的Json:
[{"elementA": [{"id:" "1", "Type": "a", "elements":[{"idOfElement":"3", "typeOfElement": "4", "otherData": "Some"}]}]}]
我正在使用Async / Await,但是問題是每個函數都會在將來解決之前進行返回,因此元素的集合將返回為空。
這是一個功能的示例:
val sensorPositionParameters: InputSensorPositionRequestValues = {
parseSensorPositionInput(sensorRequest)
}
var sensorPositionRequestDeviceSequence: LinearSeq[SensorPositionRequestDevice] = {
LinearSeq[SensorPositionRequestDevice]()
}
async {
try {
sensorPositionParameters.deviceMacAddress.foreach(
// TODO: Remove the blocking result
deviceMacAddress => Await.result(async {
val sensorHubs = await(
SensorHubRepository.sensorHubsFromDeviceMacAddress(deviceMacAddress)
)
val processedSensorHubs = await(processSensorHubs(sensorHubs))
sensorPositionRequestDeviceSequence = sensorPositionRequestDeviceSequence :+
SensorPositionRequestDevice(deviceMacAddress, processedSensorHubs)
}, Duration.Inf)
)
parseSensorPositionOutput(sensorPositionRequestDeviceSequence)
}
catch {
case ex: Exception => s"$unexpectedSensorPositionErrorPrefix ${ex.getMessage}"
case _: Throwable => s"$unexpectedSensorPositionError"
}
}
如您所見,我在代碼中添加了一個Await.result
,但我想避免阻塞。
對不起,我的英語不好,如果我的問題不清楚,我將對其進行改進。
感謝您的關注
首先,您應該將所有調用鏈接到您的foreach循環中:
val futures = sensorPositionParameters.deviceMacAddress.map (deviceMacAddress=>
for(
sensorHubs <- SensorHubRepository.sensorHubsFromDeviceMacAddress(deviceMacAddress);
processedSensorHubs <- processSensorHubs(sensorHubs)
) yield processedSensorHubs
)
這將為您提供期貨清單。 然后,您需要使用Future.sequence(futures)將此期貨列表轉換為列表的期貨。
當然,這不是一個完整的解決方案。 我希望您現在有了提示,如何避免使用await函數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.