IndexedDB 具有相同范围和模式的Dexie.js事务是否并行运行?

hs1rzwqc  于 2022-12-09  发布在  IndexedDB
关注(0)|答案(1)|浏览(297)

我正在执行类似这样的操作,db是Dexie表示例

var db = new Dexie("myDB");
    db.transaction("rw", ["table1", "table2", "table3"], async ()=>{
      console.log("[txn1] started");
      
      //function which reads something from db
      console.log("[txn1] reading from db");
      await read()
      
      // function which writes something in a nested transaction
      console.log("[txn1] writing to db");
      await write()
      
      console.log("[txn1] finished");
    })

    db.transaction("rw", ["table1", "table2", "table3"], async ()=>{
      console.log("[txn2] started");
      
      //function which reads something from db
      console.log("[txn2] reading from db");
      await read()
      
      // function which writes something in a nested transaction
      console.log("[txn2] writing to db");
      await write()
      
      console.log("[txn2] finished");
    })

由于事务处于相同的作用域和相同的模式,因此我希望回调不会并行执行,也就是说,输出应该

[txn1] started
    [txn1] reading from db
    [txn1] writing to db
    [txn1] finished
    [txn2] started
    [txn2] reading from db
    [txn2] writing to db
    [txn2] finished

但结果却像是

[txn1] started
    [txn1] reading from db
    [txn2] started
    [txn2] reading from db
    [txn1] writing to db
    [txn1] finished
    [txn2] writing to db
    [txn2] finished
k3bvogb1

k3bvogb11#

两个顶级事务回调将并行运行,直到第一个操作发生--这就是本机IDB事务处理的作用所在。本机事务不会阻塞一个操作,直到第一次请求它。如果您在事务中有三个操作,您将在实践中看到它不会'因为本地事务处理程序将阻止在同一对象存储上的两个读写事务上发生这种情况。
以下是每一步中发生的情况:
1.事务块1计划运行。
1.事务块2计划运行。
1.事务回调1开始。

  • 控制台输出:[txn 1]已启动 *
  • 控制台输出:[txn 1]从数据库阅读 *

1.事务回调1执行await read()。此时,本机事务锁定三个表以进行读/写。
1.事务回调2开始。

  • 控制台输出:[txn 2]已启动 *
  • 控制台输出:[txn 2]从数据库阅读 *

1.事务回调2执行await read()。读取操作被阻止。
1.事务1的await read()完成。

  • 控制台输出:[txn 1]正在写入数据库 *

1.事务回调1执行await write()

  • 控制台输出:[txn 1]已完成 *

1.提交事务1。
1.现在恢复事务回调2的await read()
1.事务2的await read()完成。

  • 控制台输出:[txn 2]正在写入数据库 *

1.事务回调2执行await write()

  • 控制台输出:[txn 2]已完成 *

1.提交事务2。

相关问题