我无法理解为什么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;
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的解释
您应该了解异步调用的性质.当你打电话时,程序执行不会等待service.getCurrentUser
.该PROGRAMM将继续到下一行(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;
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
我假设currentUser和isAdmin是类字段,但不是局部变量.如果isAdmin
是本地的,你可以将这个变量包装到最终的数组中:final boolean[] isAdmin = new boolean[1]
并调用它isAdmin[0]