问题
I am iterating thru an indexedDB data store, adding data to a JavaScript array. How can I tell when the cursor is at the end, so I can sort the array and act on it?
onsuccess is called when a row has been retrieved from the cursor - is there another callback when the entire cursor has been navigated?
回答1:
The result (event.target.result
) of a successful cursor request is either a cursor object or null.
If event.target.result
is set, it's the cursor, and you can access event.target.result.value
. You can then call event.target.result.continue()
to go on to the next object, if any.
If event.target.result
is not set, then there are no more objects.
For illustration, some code from a project of mine:
var collectObjects = function (request, cb) {
var objects = []
request.onsuccess = function (event) {
if (!event.target.result) return cb(null, objects)
cursor = event.target.result
objects.push(cursor.value)
cursor.continue()
}
request.onerror = function (event) {
cb(event.target.error)
}
来源:https://stackoverflow.com/questions/16639427/html5-how-to-tell-when-indexeddb-cursor-is-at-end