Skip to content

Instantly share code, notes, and snippets.

@fschwiet
Created December 10, 2013 23:55
Show Gist options
  • Save fschwiet/7902608 to your computer and use it in GitHub Desktop.
Save fschwiet/7902608 to your computer and use it in GitHub Desktop.
How to simplify this code? Promises won't help, as leaving the stack causes the IndexedDB transactions to close.
function remix(recording, frameSwitches) {
var keyRanges = [];
var lastRecordingId = null;
var lastTimeRange = Number.MIN_VALUE;
frameSwitches.switches.forEach(function(frameSwitch) {
if (lastRecordingId !== null) {
var boundStart = [lastRecordingId, lastTimeRange];
var boundEnd = [lastRecordingId, frameSwitch.time];
keyRanges.push(IDBKeyRange.bound(boundStart, boundEnd, false, true));
}
lastRecordingId = frameSwitch.recordingId;
lastTimeRange = frameSwitch.time;
});
keyRanges.push(IDBKeyRange.bound([lastRecordingId, lastTimeRange], [lastRecordingId, Number.MAX_VALUE], false, true));
return openDatabase()
.then(function(db) {
var transaction = db.transaction([recordingStoreName, framesStoreName], "readwrite");
var deferred = deferredWatchingOnerror(transaction);
var request = transaction.objectStore(recordingStoreName).put(recording);
request.onsuccess = pumpNextKeyRange;
function pumpNextKeyRange() {
if (keyRanges.length === 0) {
deferred.resolve();
return;
}
var nextKeyRange = keyRanges.shift();
var readRequest = transaction.objectStore(framesStoreName).index("byRecordingAndTime").openCursor(nextKeyRange);
readRequest.onsuccess = function(event) {
var cursor = event.target.result;
if (!cursor) {
pumpNextKeyRange();
} else {
var entry = cursor.value;
entry.recordingId = recording.id;
var writeRequest = transaction.objectStore(framesStoreName).put(entry);
writeRequest.onsuccess = function() {
cursor.continue();
};
}
};
}
return deferred.promise.finally(function() {
db.close();
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment