javascript - 如何在没有事务自动提交的情况下将 Promise 与 IndexedDB 一起使用?
问题描述
有没有办法在没有事务自动提交的情况下使用 IndexedDB 和 promises 和 async/await?我知道您不能在事务中间执行诸如获取网络数据之类的操作,但是我在网上找到的有关该主题的所有内容都表明,如果您只是将 IndexedDB 包装在 Promise 中,它仍然可以工作。
但是,在我的测试(Firefox 73)中,我发现只需将请求的onsuccess
方法包装在 Promise 中就足以使事务在 Promise 执行之前自动提交,而在使用原始 IndexedDB API 时相同的代码可以工作。我能做些什么?
这是我的代码的简化最小示例。
const {log, error, trace, assert} = console;
const VERSION = 1;
const OBJ_STORE_NAME = 'test';
const DATA_KEY = 'data';
const META_KEY = 'last-updated';
function open_db(name, version) {
return new Promise((resolve, reject) => {
const req = indexedDB.open(name, version);
req.onerror = reject;
req.onupgradeneeded = e => {
const db = e.target.result;
for (const name of db.objectStoreNames) {db.deleteObjectStore(name);}
db.createObjectStore(OBJ_STORE_NAME);
};
req.onsuccess = e => resolve(e.target.result);
});
}
function idbreq(objs, method, ...args) {
return new Promise((resolve, reject) => {
const req = objs[method](...args);
req.onsuccess = e => resolve(req.result);
req.onerror = e => reject(req.error);
});
}
async function update_db(db) {
const new_time = (new Date).toISOString();
const new_data = 42; // simplified for sake of example
const [old_data, last_time] = await (() => {
const t = db.transaction([OBJ_STORE_NAME], 'readonly');
t.onabort = e => error('trans1 abort', e);
t.onerror = e => error('trans1 error', e);
t.oncomplete = e => log('trans1 complete', e);
const obj_store = t.objectStore(OBJ_STORE_NAME);
return Promise.all([
idbreq(obj_store, 'get', DATA_KEY),
idbreq(obj_store, 'get', META_KEY),
]);
})();
log('fetched data from db');
// do stuff with data before writing it back
(async () => {
log('beginning write callback');
const t = db.transaction([OBJ_STORE_NAME], 'readwrite');
t.onabort = e => error('trans2 abort', e);
t.onerror = e => error('trans2 error', e);
t.oncomplete = e => log('trans2 complete', e);
const obj_store = t.objectStore(OBJ_STORE_NAME);
// This line works when using onsuccess directly, but simply wrapping it in a Promise causes the
// transaction to autocommit before the rest of the code executes, resulting in an error.
obj_store.get(META_KEY).onsuccess = ({result: last_time2}) => {
log('last_time', last_time, 'last_time2', last_time2, 'new_time', new_time);
// Check if some other transaction updated db in the mean time so we don't overwrite newer data
if (!last_time2 || last_time2 < new_time) {
obj_store.put(new_time, META_KEY);
obj_store.put(new_data, DATA_KEY);
}
log('finished write callback');
};
// This version of the above code using a Promise wrapper results in an error
// idbreq(obj_store, 'get', META_KEY).then(last_time2 => {
// log('last_time', last_time, 'last_time2', last_time2, 'new_time', new_time);
// if (!last_time2 || last_time2 < new_time) {
// obj_store.put(new_time, META_KEY);
// obj_store.put(new_data, DATA_KEY);
// }
// log('finished write callback');
// });
// Ideally, I'd be able to use await like a civilized person, but the above example
// shows that IndexedDB breaks when simply using promises, even without await.
// const last_time2 = await idbreq(obj_store, 'get', META_KEY);
// log('last_time', last_time, 'last_time2', last_time2, 'new_time', new_time);
// if (!last_time2 || last_time2 < new_time) {
// obj_store.put(new_time, META_KEY);
// obj_store.put(new_data, DATA_KEY);
// }
// log('finished write callback');
})();
return [last_time, new_time];
}
open_db('test').then(update_db).then(([prev, new_]) => log(`updated db timestamp from ${prev} to ${new_}`));
解决方案
围绕事务编排承诺,而不是单个请求。
如果这会导致您的设计出现问题,并且您仍想使用 indexedDB,那么围绕它进行设计。重新评估您是否需要事务安全,或者是否需要为多个请求实际重用一个事务,而不是创建多个事务,每个事务只有几个请求。
与生成具有大量请求的少量事务相比,生成具有少量请求的大量事务几乎没有开销。唯一真正关心的是一致性。
任何等待都是变相的让步。当没有请求挂起时,indexedDB 事务超时。产量会导致时间间隔,因此事务将超时。
推荐阅读
- python - 线性模型文本分类中的特征重要性,StandardScaler(with_mean=False) yes or no
- python - Pandas 数据框中一列的多个聚合以返回两列
- c++ - 即使在离开作用域之后,如何访问在 C++ 中分配在堆上的变量?
- angular - 错误地添加了服务人员。删除了它,但如何从现有的计算机上取下它?
- laravel - 在模型中需要时使用虚拟类进行测试
- css - Nginx pod 不提供 css 文件
- java - 在 NASA Worldwind 中实现 XYZ 平铺层
- django - 如何在 Django 中获取链接到另一个 HTML 模板的按钮?
- sql - 无效的 SQL 语句;在 SQL 语句中使用 IF EXISTS() 时出错,OLEDB MS ACCESS
- laravel - 如何使用 Laravel 更新选定下拉列表的值?