GWT Single threaded async callbacks

邮差的信 提交于 2019-12-06 12:22:33

#1 javascript is single-thread, but the browser is not, so the js-thread sends the xhr call to the browser to resolve it, and the browser returns the control to it inmediately.

#2 when the browser gets the response from the server, it queues the callback into the js thread, so it will be executed when js finishes whatever it could be executing now (in your case the subsequent code block)

#3 yes it will, because the single threaded execution of this block prevents the execution of any other deferred code (timeouts, callbacks) until it is finished.

With GWT-RPC, an async callback looks like this:

AsyncCallback<ResultBean> callback = new AsyncCallback<ResultBean>() {
    public void onSuccess(ResultBean result) {
        // Code to run once callback completes
    }

    public void onFailure(Throwable caught) {
        // Error handling code
    }
};

asyncService.call(callback);

// Subsequent code block

The onSuccess() method will get called once the results have been received from the server. The subsequent code block will get executed before the callback completes, because the single thread has to complete execution of the current event before it can process the next one in the queue. To make sure that some code executes after the callback completes, it should be called from the onSuccess() method.

Here's a technical explanation of how this works in a single threaded environment (found here from Thomas Broyer):

GWT-RPC makes use of RequestBuilder, which is based on XMLHttpRequest. XMLHttpRequest (XHR) uses events to communicate back with the code, so anything happening on an XHR results in an event being pushed on the event queue, and dequeued by the event loop.

See also the GWT documentation.

At the moment there is no difference between

rpc.call(mycallback);
{
   //subsequent code block
}

or

{
   // code block before
}
rpc.call(mycallback);

However, I do not see any reason to depend on such a behavior. If you want to be sure that the code block has been executed, use the second version

Suresh Atta

As the call made Asyncronously hence you don't know when the callback returns from server.

So,

when the code Server call starts the //subsequent code block starts executing ,And when the call ends the code in onSuccess code blocks starts executing .

If onSuccess code block and subsequent code block are independent there is no difference whether calling before or after the server hit.

if both are dependent

rpc.call(new AsynchCallback { 
        onSucees(){
                   //subsequent code block
                  }
   });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!