storesafe / cordova-sqlite-storage

A Cordova/PhoneGap plugin to open and use sqlite databases on Android, iOS and Windows with HTML5/Web SQL API
Other
2.15k stars 715 forks source link

asynchronous to synchronous? #347

Open tyrtok opened 9 years ago

tyrtok commented 9 years ago

Hi Im new to this.

I would like to raise a question if possible. I realized that the executesql() calls are asynchronous.

lets assuming you are building an app and you query the local sqlite for a certain value. is there any way to wait for the query to finish(outside of transaction scope)? var data =""; db.transaction(function (tx) { tx.executeSql(yourquery, [], function(tx, rs){ data = rs[0] etc; }

if (data == something ) {

../ process the data here } });

brodycj commented 9 years ago

Unfortunately there is no way for a piece of ES3/ES5-complaint Javascript code to simply stop and wait for sqlite results, or any of the other Cordova operations to finish since Cordova makes all native operations work asynchronously with callbacks. It does forces you to think about programming a bit differently, if you want to use ES3/ES5. (ES6 generators and LiveScript try to solve this problem. Also, I find the CoffeeScript syntax as well as the ES6 fat arrow to make it easier to deal with asynchronous code.)

You may want to check out Javascript Promises. Promises is a Javascript API that makes this kind of asynchronous programming easier for some programmers. There are some libraries out there, and IIRC Cordova does use a Promise library internally (not sure if it is available for your app code). A couple of resources that may help you:

MetaMemoryT commented 9 years ago

https://github.com/MetaMemoryT/websql-promise should now work with Cordova-sqlite-storage