如何解决websql中的异步问题

本文探讨了在Safari浏览器中使用HTML5数据库API时遇到的异步操作问题,并提出了一种通过`openDatabaseSync()`方法实现同步打开数据库的解决方案。此外,还提供了一个直接在回调函数中整合所有逻辑的示例代码,以简化异步调用,提高用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值