40media Pattern for wrapping an Asynchronous JavaScript function to make it synchronous


Pattern for wrapping an Asynchronous JavaScript function to make it synchronous



I'm working with a JavaScript API where most of the functions are asynchronous. The API is the WebKit JavaScript Database API which is a binding to a subset of functionality to manipulate SQLite3 databases. I understand the design decision to make things async as to not block and provide a responsive user interface. In my situation I know that my usage of the async API calls will execute fast. Since this is the case I'd like to provide my developers a cleaner and easier to use wrapper API that forces synchronous calls.

Here's the async call

db.executeSql(sqlStatement, function(result) {   // do something with result }); 

And here's what I'd like to be able to do

var result = dbWrapper.executeSql(sqlStatement); // do something with result 

Is there a design pattern/way to do this? A written or linked to code example is preferred. The target platform/broswer is Mobile Safari on the iPhone.

Thank you




Need to show only Weekday with Date UIDatePicker in iPhone

1:



iphone: creating image without allocating new memory
Sorry, JavaScript does not provide the language primitives (eg.


Including Objective C++ Type in C++ Class Definition
threads or coroutines) to make asynchronous things act synchronously or vice-versa..
How to convert time to the time zone of the iPhone device?
You generally* get one thread of execution only, so you can't get a callback from a timer or XMLHttpRequest readystatechange until the stack of calls leading to the creation of the request has completely unravelled..
Slow loading of UITableView. How know why?
So in short, you can't really do it; the approach with nested closures on the WebKit page you linked is the only way I know of to make the code readable in this situation..
How optimize sqlite query with dates & substr?
*: except in some obscure situations which wouldn't help you and are generally considered bugs.
How use sqlite + fdbm library with threading on the iPhone


Exception/Error handling in Objective-C (iPhone app)

2:


StratifiedJS allows you to do exactly that.. There's even an article on how to apply it on browser storage: http://onilabs.com/blog/stratifying-asynchronous-storage. And this is the Stratified JavaScript library it uses https://gist.github.com/613526. The example goes like:.
var db = require("webdatabase").openDatabase("CandyDB", ...); try {   var kids = db.executeSql("SELECT * FROM kids").rows;   db.executeSql("INSERT INTO kids (name) VALUES (:name);", [kids[0]]);   alert("done"); } catch(e) {   alert("something went wrong"); } 
maybe a bit late, but the tech didn't exist back then ;).


3:


You can try something like:.
function synch() {     var done = false;     var returnVal = undefined;      // asynch takes a callback method     // that is called when done     asynch(function(data) {         returnVal = data;         done = true;     });      while (done == false) {};     return returnVal; } 
But that may freeze your browser for the duration of the asynch method.... Or take a look at Narrative JavaScript: Narrative JavaScript is a small extension to the JavaScript language that enables blocking capabilities for asynchronous event callbacks.

This makes asynchronous code refreshingly readable and comprehensible.
. http://neilmix.com/narrativejs/doc/index.html. Mike.


4:


if you are using jQuery Ajax : $.ajax() . you can set the attribute of asynch to false , and then you will have a synch ajax request to the server.

.


5:


We are using GWT RPC which also has an async API.

The solution that we are currently using to make several async calls in serial is call chaining:.
callA(function(resultA) {     callB(resultA, function(resultB) {         callC(); //etc. 

}); });
This nested approach achieves what you want but it is verbose and hard to read for newcomers.

One of the approaches that we have investigated is adding the calls that we need to make to a stack and executing them in order:.
callStack = [     callA(),     callB(),     callC() ];  callStack.execute(); 
Then the callstack would manage:.
  1. Invoking the calls in serial (i.e.

    the wiring in the first example)
  2. Passing the result from one call forward to the next.
However, because Java doesn't have function references, each call on the call stack would require an anonymous class so we stopped short of such a solution.

However, you may have more success in javascript.. Good luck!.


6:


This doesn't actually implement synchronous operation of the db query, but this was my solution for easy management.

Basically use the calling function as the callback function, and test for the results argument.

If the function receives results, it parses them, if not, it sends itself as a callback to the query method..
 render: function(queryResults){   if (typeof queryResults != 'undefined'){    console.log('Query completed!');    //do what you will with the results (check for query errors here)    } else {    console.log('Beginning query...');    this.db.read(this.render); //db.read is my wrapper method for the sql db, and I'm sending this render method as the callback. 

} }


7:


I am not sure if this is the right place but I cam here searching for answers to making an synchronous calls in Firefox.

the solution would be to remove onreadystatechange callback and do a direct call.

This is what I had found and my solution synchronous call back with rest service.



82 out of 100 based on 42 user ratings 1042 reviews