Whether the action code returns a Result or a Promise, both kinds of returned object are handled internally in the same way. There is a single kind of Action, which is asynchronous, and not two kinds (a synchronous one and an asynchronous one). Returning a Promise is a technique for writing non-blocking code.
这是否意味着返回Promise<Result>
没有区别/优点或缺点而不是返回 Result
?如果玩!框架包含对 public static Result function()
的调用在 Promise
,开发人员是否有明确返回 Promise<Result>
的点? ?
最佳答案
不,明确返回 Promise<Result>
是没有意义的。 ,如果您的代码所做的是同步的,只需返回 Result
。
但是,有时您的代码会调用返回 Promise
的其他代码。因为它执行非阻塞异步操作。在这种情况下,您应该转换 promise 以从中提取您需要的信息,然后将其返回。通过将其保持为 Promise
而不是解开它 - 您不会强制线程阻塞并节省上下文切换的开销,这可能是巨大的。
例如,假设您要查询网络服务:
WSRequestHolder holder = WS.url("someUrl");
Promise<JsonNode> json = holder.get();
现在,您可以执行以下操作:
JsonNode jsonResult = json.get(); // force the program to wait
return jsonResult; // return it
但这将强制线程在阻塞 io 操作中进行上下文切换。相反,您可以直接返回一个 promise :
return json; // return the promise
并且节省上下文切换的开销,还可以使用.map
如果您需要先操纵它。
关于java - 游戏中下面这句话是什么意思!文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29646215/