-1

here's my code so far (this is using GWT):

private ArrayList<tObjects> getSuggestions(String query)
{
    // Clear previous suggestions
    Window.alert("Clearing arraylist");
    arrayList.clear();
    query = query.toUpperCase().replace(" ", "");

    RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, "xmlfile.php?query="+query);
    rb.setHeader("Content-Type", "application/x-www-form-urlencoded");

    try
    {
        rb.sendRequest(null, new RequestCallback()
        {

            @Override
            public void onResponseReceived(com.google.gwt.http.client.Request request, com.google.gwt.http.client.Response response)
            {
                Window.alert(response.getText());

                    // Do a lot of data processing here.
                    Window.alert("Adding to arraylist");
                    addToArrayList(data);


                }

            }

            @Override
            public void onError(com.google.gwt.http.client.Request request, Throwable exception)
            {
                // TODO Auto-generated method stub

            }
        });
    }
    catch(RequestException e)
    {
        Window.alert(e.toString());
    }
    Window.alert("Returning arraylist. "+arrayList.toString());
    return arrayList;
}

I receive the response correctly, but the method returns the (empty) arrayList before it is added. If i remove the arrayList.clear(), on the next ajax call I see the result of the previous call. When I look at the alerts, the fire in this order:

1) "Clearing arrayList."

2) "Returning arrayList."

3) Alert with correct response from ajax

4) "Adding to arrayList"

It seems like the method is not waiting for the ajax to complete before returning and finishing the method. How can I make it wait for the ajax & population of the arrayList before I get to the return statement?

Thanks!

4

2 に答える 2

0

非同期呼び出しとは、ノンブロッキング コードを意味します。非同期で考える必要があります。たとえば、非同期呼び出しを使用して取得したものを返す必要があるメソッドに依存しないでください。データ待たずに応答を待つようにアプリケーションを設計します。

通常、これはメソッド内にロジックをonResponseReceived()配置するか、呼び出されるコールバックを渡すか、イベントを使用することによって行われます。

于 2013-06-21T08:51:03.713 に答える