0

This question is very useful. There're some questions about calling multiple AsyncCallback but they didn't tell how to call them in a loop.

Here is my problem. I am doing a project using Gwt-platform. I got a presenter TestPresenter.java which has these codes:

@Inject
DispatchAsync dispatchAsync;

private AsyncCallback<GetDataResult> getDataCallback = new AsyncCallback<GetDataResult>() {

    @Override
    public void onFailure(Throwable caught) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onSuccess(GetDataResult result) {
       // do Something o show the gui here
    }
};

public void load_All_Gui_At_Once() {
    for(int i=0; i<5; i++) {
        GetData getDataAction=new GetData(i);
        dispatchAsync.execute(getDataAction, getDataCallback);
    }
}

The problem is that the program show the data but it showed in the wrong order. This is cos the next Async method started to run while the previous one has not finish yet.

Some suggested me to put the 2nd call inside onSuccess, but that is only for simple 2 sync calls. But in my case, I have to loop many unknown number of Async calls, then how can i do it?

4

1 回答 1

3

这是一个与此类似的问题。您所有的调用都是在同一时刻执行的,但响应时间未知,无法保证顺序。所以解决方法也差不多,在回调里面调用循环。您的代码应如下所示:

@Inject
DispatchAsync dispatchAsync;

private AsyncCallback<GetDataResult> getDataCallback = new AsyncCallback<GetDataResult>() {
  int idx = 0;

  @Override
  public void onFailure(Throwable caught) {
    // TODO Auto-generated method stub
  }

  @Override
  public void onSuccess(GetDataResult result) {
    if (result != null) {
      // do Something or show the gui here
    }
    if (idx < 5) {
      GetData getDataAction = new GetData(idx);
      dispatchAsync.execute(getDataAction, getDataCallback);
    }
    idx ++;
  }
};

public void load_All_Gui_At_Once(){
  // Start the loop, calling onSuccess the first time
  getDataCallback.onSuccess(null);
}
于 2013-07-08T14:11:29.073 回答