Indexeddb 简明教程
IndexedDB - Promise Wrapper
Promises ,就像回调函数一样,是一种在不对 javascript 的运行时线程停止的情况下告知你的代码完成异步操作时要执行什么操作的技术。
Promises, like callbacks, are a technique of telling what you want your code to perform once an asynchronous operation completes without stopping the runtime’s thread of javascript.
与在异步函数完成后提供回调函数来运行的方式不同,可以使用 promise 代替。
Instead of supplying a callback to an asynchronous function to run after it completes, promises can be used instead.
Promise 库是 Jake Archibald 创建的,它使用 promise 而不是事件。
Promise library was created by Jake Archibald and it uses promises rather than events.
使用起来比传统的 IndexedDB 更加容易。它简化了 API,同时仍然保留了 API 的结构。
It is easier to use than the traditional IndexedDB. It simplifies the API while still maintaining its structure.
这里我们仅展示了为什么我们可以使用 Promise 库的原因,要了解关于它的更多信息,您可以访问以下网站 −
Here we are showing the enhancements only as to why we can use the Promised library to know more about it you can visit the following website −
它有一些增强功能 −
It has a few enhancements −
-
IDBDatabase
-
IDBTransaction
-
IDBCursor
IDBDatabase
从对象存储获取或设置的快捷方式
Shortcuts to get or set from an object store
const value = await db.get(storeName, key);
await db.put(storeName, value, key);
从索引获取的快捷方式
Shortcuts to get from an Index
const value = await db.getFromIndex(storeName, indexName, key);
IDBTransaction
tx.store
如果事务是一个单个存储,则存储属性引用存储,否则未定义,那么我们使用
If a transaction is a single store the store property references the store or else it is undefined then we use
const tx = db.transaction('any transaction');
const store = tx.store;
tx.objectStore(storeName);
tx.done
当事务成功完成时,.done promise 解决,否则会因事务错误拒绝。
The .done promise resolves when a transaction is completed successfully else it rejects with a transaction error.
const tx = db.transaction(storeName, 'readwrite');
await Promise.all([
tx.store.add('one', 'two'),
tx.store.put('three', 'four'),
tx.done,
]);
IDBCursor
游标推进的方法为 −
The cursor advance methods are −
-
Advance
-
Continue
-
ContinuePrimaryKey
它们返回对 cursor 的 promise,否则返回 null。
They return a promise to cursor or else it returns null.
let cursor = await db.transaction(storeName).store.openCursor();
while (cursor) {
document.write(cursor.key, cursor.value);
cursor = await cursor.continue();
}