1

我对 GWT 有一个不寻常的问题。我在浏览器上编译项目后打开 .html 文件来运行它。它运行良好,直到出现以下代码行:

public static ClickHandler addBoardButtonHandler(final String name) {
    return new ClickHandler(){

        @Override
        public void onClick(ClickEvent event) {
            Window.alert("We will retrieve them!"); //this line runs
            String boardSTickets = getBoardSTickets(name); // this too
            Window.alert("We got tickets!"); // the code is never executing this line
            String boardSSwimlanes = getBoardSSwimlanes(name);
            Window.alert("We got swimlanes!");
            KanbanizerClient.showSingleBoard(boardSTickets, boardSSwimlanes);
        }

    };
}

此方法由其他方法调用:

private static Button addBoardButton(String name) {
    Button button = new Button(name);
    button.addClickHandler(HandlerManager.addBoardButtonHandler(name));
    return button;
}

这也运行正常。这是 getBoardSTickets() 方法:

protected static String getBoardSTickets(String name) {
    final List<String> ticketsJSON = new LinkedList<String>();  
    try {
            Request request = Builder.createBuilder(RequestBuilder.GET, "http://localhost:8080/Kanbanizer/boards/" + name + "/tickets").sendRequest(null, new RequestCallback(){

                @Override
                public void onResponseReceived(Request request,
                        Response response) {
                    if(response.getStatusCode() == 200){
                        ticketsJSON.add(response.getText());
                    }

                }

                @Override
                public void onError(Request request, Throwable exception) {
                    // TODO Auto-generated method stub

                }

            });
        } catch (RequestException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    return ticketsJSON.get(0);
}

谢谢 :)

4

1 回答 1

2

要了解 GWT 上下文中的 ajax - 请阅读https://developers.google.com/web-toolkit/doc/latest/tutorial/clientserver中的“进行异步调用”部分

您将 getBoardSTickets() 编程为在执行异步请求调用后返回字符串的方法是有缺陷的。不要尝试在 getBoardSTickets() 中返回异步调用的结果。

return ticketsJSON.get(0);之后立即被调用sendRequest()。由于 RequestCallback() 没有完成处理,它会抛出异常,因为 ticketJSON 将有零条目。

尝试从外部传递回调

protected static String getBoardSTickets(String name,  RequestCallback callback){
      //Code for making request
}

您的调用代码应更改为

getBoardSTickets(name, new RequestCallback(){
  //onSuccess and onFailure handling.
} )

相同的逻辑适用于所有调用server 的异步调用的方法。您不应该编程以从该方法返回请求响应的值。

于 2013-03-24T16:12:06.403 回答