如何解决websql中的异步问题

1.首先websql openDatabase()方法打开数据库的其结果必然以异步方式返回结果,openDatabaseSync()方法可以同步方式打开数据库,但是貌似safari游览器中找不到这样的一个方法。

原文:http://stackoverflow.com/questions/4052479/html5-database-api-synchronous-request

To get an object implementing DatabaseSync you have to call openDatabaseSync(...) instead ofopenDatabase(...). I don't know about the iPhone, or what the oDB object you have is, but according to spec you only get the openDatabaseSync method in a WebWorker and not in the normal web browser window. Certainly XMLHttpRequest has demonstrated that potentially-length synchronous operations in the UI thread are not a good idea.

 

2.看了老外的另外一个方案:http://stackoverflow.com/questions/3903155/synchronous-query-to-web-sql-database

发现其实可以直接写在回调函数中不必拆分成多个函数,这样就可以解决异步的问题了,如下(所有代码逻辑都在回调函数中完成):

 

functiongetFolder(id, callback) {
          vardata = [];
          ldb.transaction(function(tx) {
          tx.executeSql('SELECT * FROM folders where id=?',
              [id],
            function(tx, results) {
                if(results.rows && results.rows.length) {
                    for(i = 0; i < results.rows.length; i++) {
                        data.push(results.rows.item(i));
                    }
                }
                if( typeof(callback) == 'function') callback(data);
          },
          function(tx, error) {
              console.log(error);
          });
      });


你可能感兴趣的:(Html5,WebSql)