Created
December 10, 2013 23:55
-
-
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.
This file contains 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
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