如何等待异步http结束后再继续?
在GWT中有什么方法可以等待异步调用完成吗? 我需要响应才能继续(这是一个登录屏幕,因此成功意味着更改为实际游戏,失败意味着停留在登录屏幕中)。
这是调用:
private void execRequest(RequestBuilder builder)
{
try
{
builder.sendRequest(null, new RequestCallback()
{
public void onError(Request request, Throwable exception)
{
s = exception.getMessage();
}
public void onResponseReceived(Request request,
Response response)
{
s = response.getText();
}
});
} catch (RequestException e)
{
s = e.getMessage();
}
}
这是调用方法:`
public String check()
{
s = null;
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, baseUrl
+ "check&user=" + user + "&password=" + password);
execRequest(builder);
return s;
}
我需要 check 方法来返回响应(或错误)而不是返回 null。
我尝试了一种脑死亡的解决方案:
while (s == null);
等待调用完成,但这只是在开发模式下破坏了页面。
(chrome说页面无响应,建议杀掉它)
In GWT is there any way to wait for asynchronous call to complete?
I need the response to continue (It's a login screen so succes means changing to the actual game and failure means staying in the login screen).
Here is the call:
private void execRequest(RequestBuilder builder)
{
try
{
builder.sendRequest(null, new RequestCallback()
{
public void onError(Request request, Throwable exception)
{
s = exception.getMessage();
}
public void onResponseReceived(Request request,
Response response)
{
s = response.getText();
}
});
} catch (RequestException e)
{
s = e.getMessage();
}
}
And here is the calling method:`
public String check()
{
s = null;
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, baseUrl
+ "check&user=" + user + "&password=" + password);
execRequest(builder);
return s;
}
I need the check method to return the response (or error) and not to return null.
I tried the brain-dead solution of writing:`
while (s == null);
To wait for the call to finish but that just crushed the page in development mode.
(chrome said page is unresponsive and suggested to kill it)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
拥抱异步,而不是对抗它!
换句话说:使您的 check 方法也异步,传递回调参数而不是返回值;并将回调传递给
execRequest
(只需用对回调的调用替换对s
的每个赋值即可)。正如 Jai 所建议的那样,您不一定需要在应用程序范围的事件总线上触发事件:它有助于解耦,但这并不总是您需要/想要的。
Embrace asynchrony, don't fight it!
In other words: make your
check
method asynchronous too, passing a callback argument instead of returning a value; and pass a callback toexecRequest
(simply replace every assignment tos
with a call to the callback).You don't necessarily need to fire an event on an application-wide event bus, as Jai suggested: it helps in decoupling, but that's not always what you need/want.
您不应该以这种方式检查是否完成。这里的最佳设计实践是在登录异步调用完成时触发自定义事件。当您收到事件(通过事件总线)时,您将执行剩余的任务。
阅读 http://code.google.com/webtoolkit/articles/ mvp-architecture.html#events
You should not check for completion that way. The best design practice here is to fire a custom event when the login async call completes.. and when you receive the event (through the event bus) you do the remaining tasks.
read up on http://code.google.com/webtoolkit/articles/mvp-architecture.html#events