如何在继续之前等待异步 http 结束? [英] How to wait for async http to end before continuing?

查看:26
本文介绍了如何在继续之前等待异步 http 结束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 GWT 中有没有办法等待异步调用完成?我需要响应才能继续(这是一个登录屏幕,所以成功意味着切换到实际游戏,失败意味着停留在登录屏幕中).
这是电话:

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();
    }
}

这是调用方法:`

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);

等待调用完成,但这只是在开发模式下破坏了页面.
(chrome 说页面无响应,建议关闭)

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)

推荐答案

拥抱异步,不要对抗它!

Embrace asynchrony, don't fight it!

换句话说:让你的 check 方法也是异步的,传递一个回调参数而不是返回一个值;并将回调传递给 execRequest(只需用对回调的调用替换对 s 的每个分配).正如 Jai 建议的那样,您不一定需要在应用程序范围的事件总线上触发事件:它有助于解耦,但这并不总是您需要/想要的.

In other words: make your check method asynchronous too, passing a callback argument instead of returning a value; and pass a callback to execRequest (simply replace every assignment to s 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 结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆