← 中文资源

简体中文版本

isConnected 拦截过期更新

await 之后元素可能已被移出文档:写回前检查 isConnected,脱节节点直接丢弃本次更新,防止过期异步写入摸到幽灵节点上产生脏状态。

阅读英文原文

实现说明

底层就是函数 renderItem。 异步部分依次 await 结果,顺序可预测。

使用要点

  • document 只存在于浏览器——Node 运行时没有现成的垫片。
  • 演示输出是带标签的(dropped stale update:、applied update:),每个操作都会留下自己的一行标注。

常见问题

「isConnected 拦截过期更新」能在裸 Node.js 里跑吗?

不能——document 的家在浏览器里,Node 进程提供不了。执行时请用页面(或 DevTools 控制台)。

签名一览:async function renderItem(item)

核心语句

await Promise.resolve(); // any async gap: fetch, timer, user event
if (!row.isConnected) {
  console.log('dropped stale update:', item.title);
  return;
}

代码示例

// After an await, the element may already be gone — isConnected guards
// stale async updates before they touch detached nodes
const list = document.querySelector('#feed');

async function renderItem(item) {
  const row = document.createElement('li');
  row.textContent = item.title;
  list.append(row);

  await Promise.resolve(); // any async gap: fetch, timer, user event

  if (!row.isConnected) {
    console.log('dropped stale update:', item.title);
    return;
  }
  row.classList.add('loaded');
  console.log('applied update:', item.title);
}

renderItem({ title: 'first' });
renderItem({ title: 'second' });

// removing the second row while its update is in flight is exactly the race
list.lastElementChild.remove();