【问题标题】:Aborting Dexie.js query中止 Dexie.js 查询
【发布时间】:2021-01-14 18:17:46
【问题描述】:
在我的应用程序中,用户指定了查询的某些部分。我反应
在用户更改查询中的某些内容后立即。关于大数据
设置,这是一个问题 - 查询可能需要大约 2 秒才能完成
有时用户在查询之前应用额外的约束
完成,因此创建了一个新查询,因此用户
同时应用太多查询使系统不堪重负。什么时候
运行多个查询,即使是 2 秒的查询也变成了 30 秒的查询。
这是一个病态的极端情况,对用户来说是不可取的
一旦他们指定了所有参数,就有一个额外的按钮来触发查询。
在 Dexie 中是否有可能在查询完成之前取消查询?一世
当用户指定一个新的查询时,想取消之前的查询。
【问题讨论】:
标签:
javascript
dexie
dexiejs
【解决方案1】:
事务可以中止。我还没有测试过,但是一种方法应该是,如果您在事务中打开每个查询并将事务存储在一个状态中,这样您就可以在新事务即将触发时中止先前的事务。
function cancellableDexieQuery(includedTables, querierFunction) {
let tx = null;
let cancelled = false;
const promise = db.transaction('r', includedTables, () => {
if (cancelled) throw new Dexie.AbortError('Query was cancelled');
tx = Dexie.currentTransaction;
return querierFunction();
});
return [
promise,
() => {
cancelled = true; // In case transaction hasn't been started yet.
if (tx) tx.abort(); // If started, abort it.
tx = null; // Avoid calling abort twice.
}
];
}
那么作为使用这个辅助函数的例子:
const [promise1, cancel1] = cancellableDexieQuery(
"friends",
()=>db.friends.where('name').startsWith('A').toArray()
);
cancel1(); // Cancel the operation we just started.
const [promise2, cancel2] = cancellableDexieQuery(
"friends",
()=>db.friends.where('name').startsWith('B').toArray()
);
promise1.catch(error => {
// Expect a Dexie.AbortError
}
promise2.then(result => {
// Expect the array as result
});
免责声明:我没有测试过这段代码,它只是干编码的。如果您尝试此方法或代码 sn-ps 中是否有任何拼写错误,请回复是否是有效的解决方案。