如果我要从函数调用(全部用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
}
Run Code Online (Sandbox Code Playgroud)
我理解注释A中的内容将执行,同时非同步randomMethod将执行,B中的注释将执行.
我想知道,当randomMethod正在执行时(如果它需要足够长的时间),函数是否会返回其调用者(在本例中为方法'hello')并开始执行注释C中的代码?或者executeCallback会在返回之前等待randomMethod完成吗?
如果它是前者,假设我需要在继续评论C之前触摸randomMethod所触及的信息,我怎样才能让它"等待"以确保情况如此?
当调用异步方法时,程序不会等待该方法,这就是它们被称为异步的原因。randomMethod AsyncCallback的onSuccess或OnFailure方法不可能在B表示的代码之前执行。因为,浏览器在单线程中执行javascript代码,onSuccess或OnFailure方法在executeCallBack方法的调用者完成之后执行。
如果你想让代码B和代码C在randomMethod之后执行,你应该将它们放在Success方法上,例如;
randomClass.randomMethod(int a, int b, AsyncCallback<ReturnType>() {
onSuccess() {
// B: random code to execute after asynccallback
// C: Question lies in this range
}
}
onFailure()
});
Run Code Online (Sandbox Code Playgroud)