如果我要从一个函数调用(全部用 Java 编写):
public int hello() {
int a = 1;
executeCallback();
// C: Question lies in this range
return a;
}
public void executeCallback() {
// A: random code to execute before asynccallback
randomClass.randomMethod(int a, int b, AsyncCallback<ReturnType>() {
onSuccess();
onFailure();
});
// B: random code to execute after asynccallback
}
我知道注释 A 中的内容将执行,同时非同步 randomMethod 将执行并且 B 中的注释将执行。
不过,我想知道,当 randomMethod 正在执行时(如果它需要足够长的时间),函数是否会返回到它的调用者(在这种情况下是方法“hello”)并开始执行注释 C 中的代码?或者 executeCallback 在返回之前等待 randomMethod 完成?
如果是前者,假设我需要在我继续评论 C 之前触摸 randomMethod 触摸的信息,我怎样才能让它“等待”以确保情况如此?
最佳答案
当调用异步方法时,程序不会等待该方法,这就是它们被称为异步的原因。 randomMethod AsyncCallback onSuccess 或 OnFailure 方法无法在 B. 表示的代码之前执行。 因为浏览器在单线程中执行 javascript 代码,所以 onSuccess 或 OnFailure 方法是在 executeCallBack 方法的调用者完成后执行的。
如果你想让代码 B 和代码 C 在 randomMethod 之后执行,你应该把它们放在成功方法上,比如 ;
randomClass.randomMethod(int a, int b, AsyncCallback<ReturnType>() {
onSuccess() {
// B: random code to execute after asynccallback
// C: Question lies in this range
}
}
onFailure()
});
关于gwt - 等待响应时 GET AsyncCallback 将执行多远?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5025647/