0

如果类具有用户信息,则函数canReveal()返回 true 。ClientState如果没有,它首先尝试使用异步调用来获取该用户信息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();
}
4

1 回答 1

1

这样做的方法是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 是单线程的。

于 2012-11-05T16:52:31.357 回答