idb-request
Transform IndexedDB request-like object to a
Promise
.
Promise is a nice way to deal with primitives of IndexedDB. IDBRequest
has onsuccess
and onerror
callbacks, which perfectly map to Promise's resolve
and reject
. The same applies to oncomplete
and onerror
of IDBTransaction
.
If you're going to reuse transactions with Promise
syntax, you can't be sure that it will work in all browsers.
You need to rely on the default callback syntax or use idb-batch.
This issue is well explained in "Tasks, microtasks, queues and schedules" article.
Internally idb-request
fixes IndexedDBShim#204 issue
and allows safely iterate over index cursors.
Installation
npm install --save idb-request
Example
Using ES2016 async/await syntax.
async { const db = await const tr = db const books = tr await Promiseall const req = booksindex'byAuthor' // works everywhere const result = await console} { const books = etargetresult books books}
API
Each function returns a Promise
.
request(req, [tr])
Listen to request's onsuccess
event.
const books = db
Pass the transaction as a second argument to await completion and return the result of the request.
const tr = dbconst books = trconst req = books
mapCursor(req, iterator)
Map values over cursor. Iterator has 3 arguments:
cursor
object,result
array, which is returned on resolve. Default value is[]
.stop
resolve promise and exit earlier
const limit = 10const result = await
requestCursor(req, iterator)
Iterate through object store or index using cursor.
The same example as mapCursor
above:
const limit = 10const result = const req = books await // use result array
requestTransaction(tr)
Listen to transaction's oncomplete
event.
const tr = dbconst books = tr await Promiseall