微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

中止Dexie.js查询

如何解决中止Dexie.js查询

在我的应用程序中,用户指定查询的某些部分。我反应 用户更改查询中的内容后立即进行。大数据 集,这是一个问题-查询可能需要2秒钟才能完成 有时用户查询之前应用其他约束 完成,因此创建了一个查询,因此用户 通过同时应用太多查询使系统不堪重负。什么时候 运行多个查询,即使2秒查询变成30秒查询。 这是一个病理性的极端情况,对用户而言并不理想 一旦指定了所有参数,就会有一个额外的按钮来触发查询

Dexie是否有可能在查询结束之前取消查询?一世 想在用户指定新查询时取消上一个查询

解决方法

交易可以中止。我还没有测试过,但是一种方法应该是,如果您打开事务中的每个查询并以某种状态存储事务,那么当新事务即将触发时,您可以中止先前的事务。

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
});

免责声明:我尚未测试此代码,它只是干式编码。如果您尝试这种方法,或者代码片段中有错别字,请回答这是否是一个可行的解决方案。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。