The html5 spec for executeSql includes a success callback and a fail callback:
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM MyTable WHERE CategoryField = ?',
[ selectedCategory ],
function (tx, rs) { displayMyResult(rs); },
function (tx, err) { displayMyError(err); } );
});
If I were using jQuery, is there a way to implement this using the new jQuery promise/deferred hotness?
I just wanted to add one more example.
(function () {
// size the database to 3mb.
var dbSize = 3 * 1024 * 1024,
myDb = window.openDatabase('myDb', '1.0', 'My Database', dbSize);
function runQuery() {
return $.Deferred(function (d) {
myDb.transaction(function (tx) {
tx.executeSql("select ? as Name", ['Josh'],
successWrapper(d), failureWrapper(d));
});
});
};
function successWrapper(d) {
return (function (tx, data) {
d.resolve(data)
})
};
function failureWrapper(d) {
return (function (tx, error) {
d.reject(error)
})
};
$.when(runQuery()).done(function (dta) {
alert('Hello ' + dta.rows.item(0).Name + '!');
}).fail(function (err) {
alert('An error has occured.');
console.log(err);
});
})()
Stumbled across this question while looking for something else, but I think I have some template code that will get you started wrapping webSql queries in jQuery Promises.
This is a sample sqlProviderBase
to $.extend
onto your own provider. I've got an example with a taskProvider
and a page that would call to the taskProvider
on the page show event. It's pretty sparse, but I hope it helps point others in the right direction for wrapping queries in a promise for better handling.
var sqlProviderBase = {
_executeSql: function (sql, parms) {
parms = parms || [];
var def = new $.Deferred();
// TODO: Write your own getDb(), see http://www.html5rocks.com/en/tutorials/webdatabase/todo/
var db = getDb();
db.transaction(function (tx) {
tx.executeSql(sql, parms,
// On Success
function (itx, results) {
// Resolve with the results and the transaction.
def.resolve(results, itx);
},
// On Error
function (etx, err) {
// Reject with the error and the transaction.
def.reject(err, etx);
});
});
return def.promise();
}
};
var taskProvider = $.extend({}, sqlProviderBase, {
getAllTasks: function() {
return this._executeQuery("select * from Tasks");
}
});
var pageThatGetsTasks = {
show: function() {
taskProvider.getAllTasks()
.then(function(tasksResult) {
for(var i = 0; i < tasksResult.rows.length; i++) {
var task = tasksResult.rows.item(i);
// TODO: Do some crazy stuff with the task...
renderTask(task.Id, task.Description, task.IsComplete);
}
}, function(err, etx) {
alert("Show me your error'd face: ;-[ ");
});
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With