是否无法在异步操作中中使用cordova中调用sqlite

在一个ionic1项目中,需求要做到离线数据库功能,故使用了cordova中的sqlite插件,数据库中的数据会由首次加载app时请求后台数据获取;
但这时发现貌似无法在异步操作中调用sqlite操作,比如最简单的定时器:

$timeout(function(){
    //执行sqlite操作
},1000);

此时定时器内部的函数并不会执行,并且报错:

"InvalidStateError: DOM Exception 11: This transaction is already finalized. Transactions are committed after its success or failure handlers are called. If you are using a Promise to handle callbacks, be aware that implementations following the A+ standard adhere to run-to-completion semantics and so Promise resolution occurs on a subsequent tick and therefore after the transaction commits."

而之后尝试使用了jq的ajax并将其修改为了同步执行:

$.ajax({
    data: data,
    url: url,
    type: 'post',
    timeout: 3000,
    async: false,
    success: function(data){
        //执行sqllite操作
    },
    error: function() {
        //error
    }
})

此时就不再会报之前的一长串错误并且成功回调能够正常执行;

但是实际项目中不可能使用这种极有可能阻塞整个app的方法(比如用户信号不佳),请问是否有解决方法能够让sqlite在异步操作中执行?

阅读 3.7k
1 个回答

时间过去挺久了,讲下如何解决的这种问题,避免以后有同样踏坑的兄弟

cordova sqlite插件中貌似是存在有异步监测机制,当我们异步操作时会自动提交所有的事物(transaction),在我理解中等同于关闭了该操作线程,所以这个时候就需要重新进行打开操作

var dbOpen = window.sqlitePlugin.openDatabase({
    name: 'xxx.db',
    location: 'default'
});

然后再次在异步的回调函数中重新使用

dbOpen.transaction(function(tx){
    tx.executeSql("SQL语句...",function(tx,res){
        //do sth
    },function(tx){
        //err
    });
});

如有理解不正确,欢迎指点、讨论

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题