简体   繁体   English

玩! 框架Java Promise示例

[英]Play! framework Java Promise example

I'm reading up on Java's Play framework but don't have much experience in Java. 我正在阅读Java的Play框架,但在Java方面没有太多经验。 Can someone please explain this 有人可以解释一下吗

Promise<Double> promiseOfPIValue = computePIAsynchronously();
Promise<Result> promiseOfResult = promiseOfPIValue.map(
  new Function<Double,Result>() {
    public Result apply(Double pi) {
      return ok("PI value computed: " + pi);
    }
  }
);

I get that they're creating a promise promiseOfPiValue that's supposed to compute a double asynchronously. 我知道他们正在创建一个promise promiseOfPiValue ,应该异步计算一个double。 Then, they call map on that instance of promise to which they're passing a new instance of Function as an argument, which has implemented a the apply method. 然后,他们在promise实例上调用map ,并将新的Function实例作为参数传递给该Promise实例,该实例已经实现了apply方法。

The map part is where I get lost - how does the map method work? 地图部分是我迷路的地方-地图方法如何工作? It looks like its returning a new promise of type Result , but what's the logic of calling the apply method inside an implementation of Function ? 看起来它返回了Result类型的新诺言,但是在Function的实现内部调用apply方法的逻辑是什么?

From play documentation: 从播放文档:

Maps this promise to a promise of type B . 将此诺言映射为B类型的诺言。 The function function is applied as soon as the promise is redeemed. 兑现承诺后,就会立即应用功能function

The function: 功能:

new Function<Double,Result>() {
    public Result apply(Double pi) {
      return ok("PI value computed: " + pi);
    }
}

will convert the pi value of type Double to Result using ok() function defined in Controller as soon as computePIAsynchronously is finished. 一旦computePIAsynchronously完成,就会使用Controller定义的ok()函数将Double类型的pi值转换为Result

but what's the logic of calling the apply method inside an implementation of Function? 但是在Function的实现中调用apply方法的逻辑是什么?

This is the beauty of Promises and Scala . 这就是PromisesScala的美丽。 Scala promise framework will make sure the function is applied when promise is redeemed. Scala Promise框架将确保赎回Promise时应用该功能。 If you want to read up on this topic, I suggest grabbing sources and documentation of scala.concurrent.ExecutionContext . 如果您想阅读有关此主题的内容,建议您获取scala.concurrent.ExecutionContext源代码和文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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