@luchillo17 wrote:
Hi, i need to be able to make queries inside transactions, i have inspected the source code for SqlStorage but as far as i see i have to use the tx returned from a query to make the next one, does it work like that?
If it does i want to avoid that as it will lead to a lot of nesting when more than a few queries with transaction is needed, i did one when i was using ionic 1 but idk if it will work in ionic 2, i need to input a tx variable containig the transaction to the function queryTx and then i can use it inside queryAll, will it work?, i've commented the try with
Promise.all()
and put a workaround:UPDATE: Found the issue, i leave the code for posterity
import {Injectable} from 'angular2/angular2'; import {Http} from 'angular2/http'; import {Storage, SqlStorage, IonicPlatform} from 'ionic/ionic'; @Injectable() export class DB { constructor(http: Http) { this.db = new Storage(SqlStorage, {name: 'thadatabase'}); this.http = http; this.data = null; this.self_class = this; } getDB() { return this.db; } query(sql, args) { this.db.query(sql, args); } queryTx(tx, query, bindings) { return new Promise((resolve, reject) => { var self_class = this; tx.executeSql(query, bindings, (tx, success) => { resolve(self_class.fetchAll(success)); }, (tx, error) => { reject(error); } ); }); } queryAll(SQL) { return new Promise((resolve, reject) => { var promises = []; var self_class = this; this.getDB().transaction(function(tx) { for (var i = 0; i < SQL.query.length; i++) { promises.push( self_class.queryTx(tx, SQL.query[i], SQL.args[i]) ); } return Promise.all(promises).then(function(success) { resolve(success); }, function(err) { reject(err); }); }); }); }; fetch (result) { if (result.rows.length <= 0) return false; return result.rows.item(0); }; fetchAll (result) { var output = []; for (var i = 0; i < result.rows.length; i++) { output.push(result.rows.item(i)); } return output; };
Posts: 3
Participants: 2