我必须进行几个GWT-RPC调用。我想像这样异步启动它们。
service.s1(param1, callback1);
service.s2(param2, callback2);
service.s3(param3, callback3);我不确定如何“同步”这三个回调。下一个动作,例如调用方法nextMethod();将在三个回调完成后完成。有没有一个“最佳实践”来做到这一点?
我想要像这样构建一个小的serviceclass
public class ServiceSync
{ private boolean[] callReady;
public ServiceSync(int n)
{ callReady = new boolean[n];
for(int i=0; i<n;i++)
{ callReady[i]=false;
}
}
public boolean setReady(int i)
{ callReady[i]=true;
for(boolean b : callReady)
{ if (!b) return false;
}
return true;
}
}在回调中,我会说
if (serviceSync.setReady(myId))
{ nextMethod();}但我不确定,这是不是一个好主意。尤其是,如果两个回调“同时”调用这个scrviceclass,我不确定是否不会遇到问题。
发布于 2013-03-23 07:05:18
这似乎是可以用Promises解决的典型情况。
遵循DRY的原则,我将使用基于流行的jQuery延迟实现的gwtquery Promises解决方案,而不是编写自己的代码。
在您的示例中,您的代码可能如下所示:
// Create 3 promises to be used in RPC
PromiseRPC<String> promise1 = new PromiseRPC<String>();
PromiseRPC<String> promise2 = new PromiseRPC<String>();
PromiseRPC<String> promise3 = new PromiseRPC<String>();
// Fire the asynchronous requests
greetingService.greetServer(textToServer1, promise1);
greetingService.greetServer(textToServer2, promise2);
greetingService.greetServer(textToServer3, promise3);
GQuery
// 'when' returns a new promise which monitors all of its subordinates
.when(promise1, promise2, promise3)
// 'done' will be executed only in the case all promises succeed
.done(new Function() {
public void f() {
// each promise store its result in a fixed position of the argument list
String textFromServer1 = arguments(0, 0);
String textFromServer2 = arguments(1, 0);
String textFromServer3 = arguments(2, 0);
}
});
// If you want you could fire requests here instead than above发布于 2013-03-23 03:57:36
声明一个带有回调状态的接收器,类似于:
public class CallResultReceiver {
boolean call1Done, call2Done, call3Done;
public void onCall1Success() {
call1Done = true;
if (call1Done && call2Done && call3Done) { doGreatThings(); }
}
public void onCall2Success() {
call2Done = true;
if (call1Done && call2Done && call3Done) { doGreatThings(); }
}
public void onCall3Success() {
call3Done = true;
if (call1Done && call2Done && call3Done) { doGreatThings(); }
}
}发布于 2013-03-23 15:28:27
他是Parallel asynchronous calls in GWT上最好的文章
通过编写一个简单的ParentCallBack,你可以让你的事情变得简单而高效。
public void someGwtClientSideMethod() {
SomeServiceAsync someService = GWT.create(SomeService.class);
ParallelCallback fooCallback = new ParallelCallback();
ParallelCallback barCallback = new ParallelCallback();
ParentCallback parent = new ParentCallback(fooCallback, barCallback) {
public void handleSuccess() {
doSomething(getCallbackData(0), getCallbackData(1));
}
};
someService.foo(fooCallback);
someService.bar(barCallback);
} 这是Code for Parent Callback。
https://stackoverflow.com/questions/15578048
复制相似问题