Fake a GWT Synchronous RPC call

前端 未结 3 1142
余生分开走
余生分开走 2020-12-11 06:26

First of all, I know that doing a synchronous call is \"wrong\", and know that \"is not possible\".

But, in a situation a lot complex (i dont know how to explain), i

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-11 07:15

    GWT calls XMLHttpRequest.open() whith true as its third parameter which means the call will be asynchronous. I solved a similar need for testing purposes just forcing this third parameter to be always false:

    private static native void fakeXMLHttpRequestOpen() /*-{
       var proxied = $wnd.XMLHttpRequest.prototype.open;
    
       (function() {
           $wnd.XMLHttpRequest.prototype.open =
               function() {
                    arguments[2] = false;
                    return proxied.apply(this, [].slice.call(arguments));
                };
            })();
    }-*/;
    

    After invoking fakeXMLHttpRequestOpen(), any further use of XMLHttpRequest will act synchronously. For instance:

    remoteSvc.getResult(new AsyncCallback() {
        @Override
        public void onSuccess(String result) {
            GWT.log("Service called!");
        }
    
        @Override
        public void onFailure(Throwable caught) {
            GWT.log("Service failed...");
        }
    }
    
    GWT.log("Last message");
    

    will allways render:

    Service called!
    Last message
    

    See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open for XMLHttpRequest.open() specification.

提交回复
热议问题