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 Definitionthreads 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* receive one thread of execution only, so you can't receive 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 did 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 any obscure situations which wouldn't guidance 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 did 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 case 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("any thing went wrong"); } 
maybe a bit late, although the tech didn't exist back then ;).

3:

You must try any thing like:.
function synch() {     var done = false;     var returnVal = undefined;      // asynch takes a callback method     // this is called when done     asynch(function(data) {         returnVal = data;         done = true;     });      while (done == false) {};     return returnVal; } 
But this 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 this 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 must set the attrialthough e 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 quick fix this i 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 although it is verbose and hard to read for newcomers. One of the approaches this i have investigated is adding the calls this i 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, for the reason this Java doesn't have function references, each call on the call stack would require an anonymous class so i 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, although this was my quick fix 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!');    //did  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 although I cam here searching for answers to making an synchronous calls in Firefox. the quick fix would be to remove onreadystatechange callback and did a direct call. This is what I had found and my quick fix synchronous call back with rest service.


82 out of 100 based on 42 user ratings 1042 reviews