- IndexedDB API is callback-based: JavaScript is single-threaded. A blocking API would block the page during request processing. IndexedDB API is non-blocking. The first drafts of IndexedDB were in 2009 and implementations became available in 2011. Async functions reached main browsers late in 2016. Without async, a non-blocking JavaScript API is callback-based. An example of using callbacks with IndexedDB is shown in the code for opening a database.
- IndexedDB API is very limited: NoSQL databases usually provide a flexible DSL for querying. IndexedDB gives few tools. To get data, you can use
getAll()
,get()
,index().get()
, etc. NoJOIN
,LIMIT
,AND
, orOR
. All logic becomes a mess of JavaScript method calls. An example of getting the last items with a specific limit is shown. - IndexedDB transactions autocommit: In many languages, a transaction automatically commits when the object goes out of scope. IndexedDB is similar. Transactions are tied to the event loop. If a transaction is not used after it is made, it becomes inactive. The only way to keep a transaction active is to make a request on it. You cannot hold a transaction over an await point and cannot opt out of this behavior. An example of implementing a progress bar shows the issue with transaction autocommit.
- IndexedDB lies about transaction lifetimes: ChatGPT suggested running a loop in the background to keep the transaction alive by dispatching dummy requests. But this did not work as expected. The transaction was not committed even though
keepTransactionAlive()
was generating requests. It shows that the description of transaction lifetimes is misleading. - The Solution: Once you return to the event loop, the transaction rejects new requests except those in a callback. The solution is to use a function like
nonBlockingPuts()
to gradually dispatch PUT requests while ensuring new requests are done from theonsuccess
callback. This works but is not easily mapped toasync
code.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。