具有相同作用域和模式的Dexie.js事务是否并行运行



我正在做这样的事情,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

两个顶级事务回调将并行运行,直到第一个操作发生-这就是本机IDB事务处理的作用所在。本机事务直到第一个请求才阻止操作。如果您在事务中有三个操作,您会在实践中看到它不是并行运行的,因为本机事务处理程序将阻止在同一对象存储上的两个读写事务上发生这种情况。

以下是每一步都会发生的事情:

  1. 事务块1计划运行。

  2. 事务块2计划运行。

  3. 事务回调1开始。

    控制台输出:[txn1]已启动

    控制台输出:[txn1]从数据库读取

  4. 事务回调1执行CCD_ 1。此时,本机事务会锁定这三个表进行读/写操作。

  5. 事务回调2开始。

    控制台输出:[txn2]已启动

    控制台输出:[txn2]从数据库读取

  6. 事务回调2执行CCD_ 2。读取操作被阻止。

  7. 事务1的CCD_ 3完成。

    控制台输出:[txn1]写入db

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

    控制台输出:[txn1]完成

  9. 事务1已提交。

  10. 现在恢复事务回调2的CCD_ 5。

  11. 事务2的CCD_ 6完成。

    控制台输出:[txn2]写入数据库

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

    控制台输出:[txn2]完成

  13. 事务2已提交。

最新更新