下面的语句是什么意思from play!文档?
What is the meaning of the following statment from play! documentation?
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
没有 difference/advantage 或缺点?如果玩!框架将对 public static Result function()
的调用包含在 Promise
中,开发人员明确返回 Promise<Result>
是否有意义?
不,显式 returning a Promise<Result>
没有意义,如果你的代码只是同步 return a Result
。
但是,有时您的代码会调用其他 return 是 Promise
的代码,因为它执行 非阻塞异步操作 。在那种情况下,您应该转换承诺以从中提取您需要的信息,然后 return 它。通过将它保持为 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 操作中进行上下文切换。相反,您可以 return 直接承诺:
return json; // return the promise
并且节省了上下文切换的开销,如果需要先操作的话也可以使用.map
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
没有 difference/advantage 或缺点?如果玩!框架将对 public static Result function()
的调用包含在 Promise
中,开发人员明确返回 Promise<Result>
是否有意义?
不,显式 returning a Promise<Result>
没有意义,如果你的代码只是同步 return a Result
。
但是,有时您的代码会调用其他 return 是 Promise
的代码,因为它执行 非阻塞异步操作 。在那种情况下,您应该转换承诺以从中提取您需要的信息,然后 return 它。通过将它保持为 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 操作中进行上下文切换。相反,您可以 return 直接承诺:
return json; // return the promise
并且节省了上下文切换的开销,如果需要先操作的话也可以使用.map