将GWT异步调用(DispatchAsync)转换为同步调用
如果类将GWT异步调用(DispatchAsync)转换为同步调用,gwt,asynchronous,login,synchronous,gwtp,Gwt,Asynchronous,Login,Synchronous,Gwtp,如果类ClientState包含用户信息,则函数canReveal()返回true。如果没有,它首先尝试使用对GetUser的异步调用获取该用户信息。如果,我需要在中做的是以某种方式等待该异步调用返回(onSuccess),这样我就可以检查ClientState是否现在拥有用户信息。我该怎么做?谢谢 public class MyGatekeeper implements Gatekeeper{ private DispatchAsync dispatcher; @Inject public
ClientState
包含用户信息,则函数canReveal()
返回true。如果没有,它首先尝试使用对GetUser
的异步调用获取该用户信息。如果,我需要在中做的是以某种方式等待该异步调用返回(onSuccess
),这样我就可以检查ClientState
是否现在拥有用户信息。我该怎么做?谢谢
public class MyGatekeeper implements Gatekeeper{
private DispatchAsync dispatcher;
@Inject
public MyGatekeeper(DispatchAsync dispatcher) {
this.dispatcher = dispatcher;
}
@Override
public boolean canReveal() {
if(ClientState.isUserLoggedin()==false) {
dispatcher.execute(new GetUser(Window.Location.getHref()),
new DispatchCallback<GetUserResult>() {
@Override
public void onSuccess(GetUserResult result) {
if (!result.getErrorText().isEmpty()) {
Window.alert(result.getErrorText());
return;
}
ClientState.setUserInfo(result.getUserInfo());
}
});
return ClientState.isUserLoggedin(); // WAIT till onSuccess returns!
}
}
return ClientState.isUserLoggedin();
}
公共类MyGatekeeper实现了Gatekeeper{
私有调度异步调度;
@注入
公共MyGatekeeper(DispatchAsync dispatcher){
this.dispatcher=dispatcher;
}
@凌驾
公共布尔值canReveal(){
if(ClientState.isUserLoggedin()==false){
dispatcher.execute(新的GetUser(Window.Location.getHref()),
新DispatchCallback(){
@凌驾
成功时公共无效(GetUserResult){
如果(!result.getErrorText().isEmpty()){
alert(result.getErrorText());
返回;
}
setUserInfo(result.getUserInfo());
}
});
return ClientState.isUserLoggedin();//等待onSuccess返回!
}
}
返回ClientState.isUserLoggedin();
}
方法是让canReveal
接受回调
:
public void candiscover(回调cb){
如果(!ClientState.isUserLoggedIn()){
execute(…,new DispatchCallback(){
@凌驾
成功时公开作废(结果){
cb.onSuccess(result.isgoodorwhich());
}
});
}否则{
cb.onSuccess(true);//用户已登录
}
}
不幸的是,没有办法告诉GWT“等待”异步回调,因为这基本上会冻结JS的执行,因为JS是单线程的。谢谢!但这样我就不能返回布尔值,对吗?函数必须始终为null?它可以返回您想要的任何内容,但它无法返回回调是否成功,因为在函数返回时,这并不知道,只有在回调完成后才能返回。谢谢!那么回到我原来的问题,我们可以说DispatchAsync回调完成后不可能返回布尔值,对吗?如果从回调中调用return false
,这将是一个编译错误(因为方法是void
)--不管怎样,这都不是您想要的。因此,是的,您不能从回调中“返回”。请小心尝试从典型的异步XHR进行同步调用。同步XHR将在将来被弃用。
public void canReveal(Callback<Boolean> cb) {
if (!ClientState.isUserLoggedIn()) {
dispatcher.execute(..., new DispatchCallback<Result>() {
@Override
public void onSuccess(Result result) {
cb.onSuccess(result.isGoodOrWhatever());
}
});
} else {
cb.onSuccess(true); // User is logged in
}
}