Thursday, April 19, 2007

DWR's async trick


function submitUserAction() {
sdgControlSelectedRows (userGrid, method);
sdgRequestRows (userGrid);
}

First line delete some rows, second line requests lasted rows after udpate. Both using DWR invocation.It is surprising to see that the rows on the table not changed althought the selected rows are deleted on server side unless we intentionly refresh/reload the page. It is due to the asynchronous nature of AJAX call. 2nd statement is executed before the 1st one finished -- i.e, before the row deletion. Both method invocations are queued in ajax engine, and invoke server side in order, however, server's response may come back in any order, thus, 1st request involved DB operation and take longer time and 2nd request always come back earlier and its callback invoked first. It results in the table not being refresh.

The solution is to add them to a batch and treated as an atomic request, similar to a transaction.

function sdgControlSelectedRows (gridObject, method) {
if (! dwr.engine._batch) {
DWREngine.beginBatch ();
gridObject.gridServer.controlSelectedRows (method, {
callback: function (response) {
if (response != 'success') {
dojo.event.topic.publish("actionMessageTopic", {message: response, type: "ERROR", delay: 4000});
}
},
errorHandler: function (message) {}
});
sdgGetRows (gridObject, "control");

DWREngine.endBatch();
}

No comments: