繁体   English   中英

应对Scala中的期货

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM