为什么在事件侦听器中间等待的异步函数会删除事件的状态和阶段?
为什么在事件侦听器中间等待的异步函数会删除事件流的状态和阶段?可以保留吗?
例如,
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
并不是等待承诺“放弃”它,而是事件继续冒泡调用
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 thecurrentTarget
when running handlers with the same event object at different elements, and when reaching the root of the document it becomesundefined
. Then when you async code comes back to look at theevent
again later, it will already have been changed. The same happens when usingsetTimeout
.