为什么在事件侦听器中间等待的异步函数会删除事件的状态和阶段?

发布于 2025-01-10 07:33:49 字数 776 浏览 0 评论 0 原文

为什么在事件侦听器中间等待的异步函数会删除事件流的状态和阶段?可以保留吗?

例如,

button.addEventListener("click", async (event) => {
  eventSnapshots.push({
    title: "Sync",
    object: extract(event)
  });

  syncFn(event);
  await asyncFn();
  syncFn(event);

  writeToElement(eventSnapshots, view);
});

事件流的快照将类似于:

Sync:
{
  "phase": 2,
  "currentTarget": {},
  "path": 5,
  ...
}
SyncFn:
{
  "phase": 2,
  "currentTarget": {},
  "path": 5,
  ...
}

//await AsyncFn

SyncFn:
{
  "phase": 0,
  "currentTarget": null,
  "path": 0,
  ...
}

(https://codesandbox.io/s/pense-hill-nzxvnl?file=/src/index.js:514-745)

Why an async function, that is being awaited in the middle of the event listener, drops the state and the phase of the Event flow? Is it possible to keep it?

For example,

button.addEventListener("click", async (event) => {
  eventSnapshots.push({
    title: "Sync",
    object: extract(event)
  });

  syncFn(event);
  await asyncFn();
  syncFn(event);

  writeToElement(eventSnapshots, view);
});

The snapshot of the events' flow would be something like that:

Sync:
{
  "phase": 2,
  "currentTarget": {},
  "path": 5,
  ...
}
SyncFn:
{
  "phase": 2,
  "currentTarget": {},
  "path": 5,
  ...
}

//await AsyncFn

SyncFn:
{
  "phase": 0,
  "currentTarget": null,
  "path": 0,
  ...
}

(https://codesandbox.io/s/pensive-hill-nzxvnl?file=/src/index.js:514-745)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

记忆で 2025-01-17 07:33:49

并不是等待承诺“放弃”它,而是事件继续冒泡调用 async 侦听器函数后,无需等待它返回的 Promise。当在不同元素上运行具有相同事件对象的处理程序时,以及当到达文档的根目录时,它变为未定义。然后,当您稍后返回异步代码再次查看事件时,它已经被更改了。 使用 setTimeout 时也会发生同样的情况。

It's not that awaiting the promise "drops" it, but just that the event continues to bubble after calling your async listener function, without waiting for the promise returned by it. Bubbling automatically changes the currentTarget when running handlers with the same event object at different elements, and when reaching the root of the document it becomes undefined. Then when you async code comes back to look at the event again later, it will already have been changed. The same happens when using setTimeout.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文