Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
aSyncSelectStatementCallback
/*
First draft at making an asynchronous method for returning a large SELECT result from SQLite in Firefox.
As part of a discussion here:
https://bugzilla.mozilla.org/show_bug.cgi?id=608142
Aiming to be an expansion of:
https://developer.mozilla.org/en/storage#Asynchronously
*/
function aSyncSelectStatementCallback()
{
this.rowsPerInterval = 1; // may want to experiment with for speed
this.timePerInterval = 1; // may want to experiment with for speed
this.intervals = [];
}
aSyncSelectStatementCallback.prototype =
{
// errors
handleError : function(aError) { Components.utils.reportError(aError.message); },
// Only use this to listen to cancel/error messages.
// REASON_FINISHED is sent when all intervals have started, not when they are actually done, use handleFinished for that
handleCompletion : function(aReason)
{
if (aReason == 0 && this.intervals.length==0)
this.handleFinished();
},
// When all rows have been processed and all intervals are finished
handleFinished : function() { },
// Processes each row on against the event loop
handleResult : function(aResultSet)
{
var c = this.intervals.length;
this.intervals[c] = true;
var interval = this.setInterval(function()
{
let row;
for(let i=0; i<this.rowsPerInterval; i++)
{
row = aResultSet.getNextRow();
if (row)
this.handleRow(row);
else
{
this.clearTimeout(interval);
this.intervals[c] = false;
// check if all intervals have completed
// start at end, assuming they get completed from first to last
for(let i=this.intervals.length-1; i>=0; i--)
{
if (this.intervals[i])
return;
}
// all intervals are completed
this.handleFinished();
return;
}
}
}, this.timePerInterval, this);
},
// interval methods
setInterval : function(func, time)
{
let callback = {obj:this, notify:function(){func.call(this.obj)}};
let timer = Components.classes["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer);
timer.initWithCallback(callback, time, Components.interfaces.nsITimer.TYPE_REPEATING_SLACK);
return timer;
},
clearTimeout : function(timer)
{
if (timer)
timer.cancel();
return timer;
}
}
// example function to call when all of the results have been fetched
function hereAreYourNames(names)
{
alert( names );
}
// Create the callback and define the methods for handling each row
var callback = new aSyncSelectStatementCallback();
callback.names = [];
callback.handleRow = function(aRow) {
this.names.push( aRow.getResultByName("first_name") );
}
callback.handleFinished = function() {
hereAreYourNames(this.names);
}
// Execute the SQLite statement
statement.executeAsync(callback);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.