-
-
Save krackers/2dcc2bd2833941cdfba291d83c75aba8 to your computer and use it in GitHub Desktop.
HTML5 Promise-based WebSQL query convenience-function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // https://github.com/Philzen/WebSQL-Polyfill | |
| // https://github.com/jakearchibald/es6-promise | |
| /** | |
| * Usage: | |
| * var db = new DB('demo', '1.0', 'Demo', 2 * 1024 * 1024); | |
| * db.query('SELECT * FROM mytable') | |
| * .then(function(res){ | |
| * console.log(res.rows); | |
| * }, function(err){ | |
| * console.error(err); | |
| * }); | |
| * | |
| */ | |
| function DB(name, version, title, size){ | |
| this.db = openDatabase(name, version, title, size); | |
| } | |
| DB.prototype.query = function(sql, params){ | |
| var db = this.db; | |
| return new Promise(function(resolve, reject){ | |
| if (!db) return reject('no database.'); | |
| db.transaction(function(tx){ | |
| tx.executeSql(sql, params||[], function(tx,res){ | |
| // tidy up | |
| var rows = []; | |
| for(var i=res.rows.length; i; i--){ | |
| rows.unshift(res.rows.item(i-1)); | |
| } | |
| var out = {rows:rows, rowsAffected:res.rowsAffected}; | |
| // don't worry about no insertId | |
| try{ out.insertId = res.insertId; }catch(e){} | |
| resolve(out); | |
| }, function(tx, err){ | |
| reject(err.message); | |
| }); | |
| }); | |
| }); | |
| }; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment