IndexedDB 的 put 成功后,什么时候才算写入完成?

作者:小圆点

时间:2026-11-30

浏览:154

IndexedDB 的 put 请求成功后,事务仍可能回滚。对照两次写入的读回结果,看看草稿保存提示该等哪个事件。

文章目录

离线编辑器刚提示「草稿已保存」,刷新后正文却回到旧版本。先看看这条提示是在哪儿显示的。如果它写在 put() 的 success 回调里,就显示早了。到这一步,浏览器处理完了这条写入请求,整个事务还有可能回滚。

比如,正文和列表里的修改时间分别存成两条记录,在同一个事务里更新。正文的 put() 先成功,紧接着更新时间的请求报错,错误事件的默认行为也没有被阻止。整个事务随即中止,先前写入的正文一起回滚。刷新后看到旧正文,和控制台里那条「写入成功」并不矛盾。那条日志记的是一条请求的结果。

两次 put() 都成功,读回来的值一样吗?

用两次写入就能看出差别。第一次在 success 回调里主动调用 abort(),第二次让事务正常提交。每次等写事务结束,再新开一个只读事务查刚写过的键。可以把下面这段代码粘到 HTTPS 测试页的控制台。它会在当前站点创建演示数据库,每次写入都用新键,避免读到以前留下的记录。

function openDemoDb() {
  return new Promise((resolve, reject) => {
    const open = indexedDB.open("idb-commit-demo", 1);
    open.onupgradeneeded = () => {
      open.result.createObjectStore("entries");
    };
    open.onsuccess = () => resolve(open.result);
    open.onerror = () => reject(open.error);
  });
}

async function compareWrite(db, shouldAbort) {
  const key = crypto.randomUUID();
  const label = shouldAbort ? "回滚" : "提交";
  const outcome = await new Promise((resolve, reject) => {
    const tx = db.transaction("entries", "readwrite");
    tx.oncomplete = () => resolve("complete");
    tx.onabort = () => {
      if (shouldAbort && tx.error === null) {
        resolve("abort");
        return;
      }
      reject(tx.error ?? new Error("写入事务已中止"));
    };

    const write = tx.objectStore("entries").put("saved", key);
    write.onsuccess = () => {
      console.log(`[${label}] put success`);
      if (shouldAbort) tx.abort();
    };
  });
  console.log(`[${label}] tx ${outcome}`);

  const value = await new Promise((resolve, reject) => {
    const tx = db.transaction("entries", "readonly");
    const read = tx.objectStore("entries").get(key);
    read.onsuccess = () => resolve(read.result);
    read.onerror = () => reject(read.error);
  });
  const displayValue = value === undefined ? "undefined" : JSON.stringify(value);
  console.log(`[${label}] new tx get -> ${displayValue}`);
}

(async () => {
  const db = await openDemoDb();
  try {
    await compareWrite(db, true);
    await compareWrite(db, false);
  } finally {
    db.close();
  }
})().catch(console.error);
回滚组打印 put success 和 tx abort,读回 undefined。提交组打印 put success 和 tx complete,读回字符串 saved。
预期控制台输出

第一组照样打印了 put success,可事务已经回滚。随后那次 get() 正常完成,返回 undefined,因为这个新键下没有记录。第二组等到 complete 后读回了字符串 "saved"。读回这一步要放在新事务里。在原来的写事务里,可以读到自己还没提交的改动。

什么时候显示「已保存」?

草稿编辑器发起写入时先显示「保存中」。等写事务触发 complete,再显示「已保存」并更新最后保存时间。收到 abort 时,结束「保存中」状态,保留编辑器里的正文,让用户重试。创建事务或调用 put() 如果同步抛错,也要直接走这条失败处理路径。

排查「刚保存就丢了」时,给同一次保存的请求日志和事务日志带上同一个编号。找到那条 put success,再找同编号的事务是以 complete 还是 abort 结束的。遇到 abort,就接着查同一事务里的请求错误,以及有没有代码主动中止了事务。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章