You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

IndexedDB执行add后立即get:复用事务是否安全?

是否需要为get操作创建新事务?

不需要额外创建新事务,你的代码写法是安全的。

原因很简单:在add请求的success回调里,当前的readwrite事务还处于活跃状态,并没有完成。IndexedDB的事务会在所有关联的请求都处理完毕后才会提交,所以此时复用同一个事务执行get操作完全没问题,而且效率更高——不用额外开启新事务的开销。

不过要注意一个边界情况:如果你的get操作逻辑非常复杂,或者后续还有其他异步操作(比如等待一个外部API请求),那事务可能会因为超时被浏览器自动终止,这种情况下才需要考虑拆分事务。但就你当前的代码而言,只是简单的同步执行get,完全没问题。

你的代码运行正常也验证了这一点,Chrome的输出也显示get能正确获取到刚插入的数据,因为同一个事务内的操作是原子性的,能保证数据的一致性。

你的代码示例:

// this is only called after the 'tasks' object store has been opened
const todoIDB = requestIDB.result
const transaction = todoIDB.transaction(["tasks"], "readwrite")
const todoStore = transaction.objectStore("tasks")
const addRequest = todoStore.add({text:txt_val})
addRequest.addEventListener("success", ()=>{
  console.log("Added " + "#" + addRequest.result + ": " + txt_val)
  // should I add a new transaction, etc. here?
  const getRequest = todoStore.get(addRequest.result)
  getRequest.addEventListener("success", ()=>{
    console.log("Found " + JSON.stringify(getRequest.result))
  })
})

Chrome浏览器输出:

Added #18: aaa
Found {"text":"aaa","id":18}
Added #19: bbb
Found {"text":"bbb","id":19}

内容的提问来源于stack exchange,提问作者AndyS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 15:05:15