简体   繁体   中英

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

Sorry, JavaScript does not provide the language primitives (eg. threads or coroutines) to make asynchronous things act synchronously or vice-versa.

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.

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.

*: except in some obscure situations which wouldn't help you and are generally considered bugs

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 ;)

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

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.

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 (ie 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!

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.
  }
 }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM