我无法理解为什么gwt rpc AsyncCallback之后的代码不会被执行?
例如我有接口AppService扩展RemoteService,所以我将有AsyncAppService进行异步调用。
以下代码
AppServiceAsync service = GWT.create (AppService.class);
service.getCurrentUser(new AsyncCallback<Employee>(){
public void onFailure(Throwable caught) {
}
public void onSuccess(Employee result) {
currentUser = result;
}
});
// if i have the code after the above call, these code will not be execute, what is the problem
//code following will not be executed if they are in the same function.
boolean isAdmin = false;
if(currentUser!=null){
if(currentUser.getUserRole().equals("ROLE_ADMIN") ||
currentUser.getUserRole().equals("ROLE_MANAGER")){
isAdmin = true;
}
}
感谢您的解释
答案 0 :(得分:5)
您应该了解异步调用的性质。当您致电service.getCurrentUser
时,程序执行不会等待。程序将继续到下一行(boolean isAdmin = false
),并且在(currentUser == null)
执行方法getCurrentUser
之前有效。您应该将未执行的代码块移动到onSuccess
处理程序
此示例应如下所示:
service.getCurrentUser(new AsyncCallback<Employee>(){
public void onFailure(Throwable caught) {
}
public void onSuccess(Employee result) {
currentUser = result;
if (currentUser != null) {
if (currentUser.getUserRole().equals("ROLE_ADMIN") ||
currentUser.getUserRole().equals("ROLE_MANAGER")) {
isAdmin = true;
}
}
}
});
我假设currentUser和isAdmin是类字段,但不是局部变量。如果isAdmin
是本地的,那么您可以将此变量包装到最终数组中:final boolean[] isAdmin = new boolean[1]
并将其称为isAdmin[0]
答案 1 :(得分:1)
想象一下,你是过去非计算机化股票/商品市场的经纪人。让我们假设它以下列方式运作。
这是星期一上午9点30分。你按顺序完成了这些计划。事实上,你是如此有经验,它被编入你的程序:
程序BuyAlBanySteel(500):
节目喝咖啡
警告你必须处理:接听电话至少需要10分钟,甚至一小时。它是异步的。你知道它需要多长时间但不确定。
所以这是你早上的顺序计划:
让我问你,你将如何构建你的工作流程?你会用这种方式构建它吗?假设每个任务都会花费你一分钟的时间来执行。
9.31 am
Send offer(
buy = 500 AlbanySteel
messenger = annie
When annie comes back, analyse offer.
Pour Annie a cup of tea.
)
9.32 am
if (annie has an agreeable offer) buy 500 AlbanySteel.
9.33 am
Pour Coffee.
9.34
Drink Coffee.
当然你不能。原因是以下一行
9.32 am
if (annie has an agreeable offer) buy 500 AlbanySteel.
将无法正常执行。它似乎没有被执行,因为安妮不会再回来提供报价。可能需要她再过10分钟或一小时才能收到报价。
所以,这就是你必须执行工作流程的方法
9.31 am
Send offer(
buy = 500 AlbanySteel
messenger = annie
when annie comes back,
analyse offer.
Pour Annie a cup of tea.
if (annie has an agreeable offer) buy 500 AlbanySteel.
)
9.33 am
Pour Coffee.
9.34
Drink Coffee.
那么,在GWT伪代码中,您会选择执行哪一个?
你会执行这个:
BuyAlbanySteelAsync albanyService = GWT.create(BuyAlbanySteel.class);
albanyService.getOffer(
new Task<Annie>(){
onFailure(Annie){Do nothing}
OnSuccess(Annie){
analyse offer.
Pour Annie a cup of tea.
}
}
);
if(Annie has agreeable offer)
buy the stock.
或者这个:
BuyAlbanySteelAsync albanyService = GWT.create(BuyAlbanySteel.class);
albanyService.getOffer(
new Task<Annie>(){
onFailure(Annie){Do nothing}
OnSuccess(Annie){
analyse offer.
Pour Annie a cup of tea.
if(Annie has agreeable offer)
buy the stock.
}
}
);