将GET异步调用(Dispatch_Async)转为Synchronous

时间:2012-11-05 16:47:11

标签: gwt asynchronous login synchronous gwtp

如果类canReveal()具有用户信息,则函数ClientState将返回true。如果没有,它首先尝试使用对GetUser的异步调用来获取该用户信息。我需要在IF内做的是等待,直到这个异步调用返回(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();
}

1 个答案:

答案 0 :(得分:2)

执行此操作的方法是让canReveal获取Callback<Boolean>

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
  }
}

不幸的是,没有办法告诉GWT“等待”异步回调,因为这基本上会冻结JS执行,因为JS是单线程的。