javascript - event.waitUntil 在 Service Worker 中做什么以及为什么需要它?

标签 javascript promise dom-events service-worker

MDN 建议您执行以下操作来创建和填充服务工作线程缓存:

this.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open('v1').then(function(cache) {
      return cache.addAll([
        '/sw-test/',
        '/sw-test/index.html',
        ... etc ...
      ]);
    })
  );
});

我不明白该代码。 waitUntil 方法也有文档记录,上面的代码似乎是它目前存在的唯一目的:

The ExtendableEvent.waitUntil() method extends the lifetime of the event. When called in an EventHandler associated to the install event, it delays treating the installing worker as installed until the passed Promise resolves successfully. This is primarily used to ensure that a service worker is not considered installed until all of the core caches it depends on are populated.

我不明白的是:

  • waitUntil 通常如何影响代码流?它会阻止事件传播直到它的 promise 得到解决吗?
  • 为什么在打开工作缓存的情况下需要它?

我问这个问题是因为我对上面的代码有疑问,我想理解它。

最佳答案

正如描述所说:

the ExtendableEvent.waitUntil() method extends the lifetime of the event.

如果您不在方法内调用它,则服务工作线程可能随时停止(请参阅 the specification )。

因此,waitUntil 方法用于告诉浏览器不要终止 Service Worker,直到传递给 waitUntil 的 Promise 得到解决或拒绝。

关于您的具体问题:

  • 对于 installactivate 事件,它会延迟 Service Worker 到 installed 的状态切换已激活(请参阅 specification of the waitUntil method ,特别是该段落的最后一部分)。
  • 我认为我的答案的其余部分已经回答了为什么需要它。

关于javascript - event.waitUntil 在 Service Worker 中做什么以及为什么需要它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37902441/

相关文章:

javascript - Promise.all()的回调什么时候触发

javascript - 如何使用 JavaScript 中的 Promise 进行状态更新?

javascript - 事件监听超时-node.js

javascript - 在 React 中,onChange 和 onInput 有什么区别?

javascript: getAverageAge 所有对象

javascript - 隐藏的 div 不会显示悬停图像

JavaScript 在 while 循环中等待异步函数

asp.net - 如何让客户端脚本在 ASP.NET 回发上执行? (来自更新面板)

javascript - 如何在 jQuery 中获取所有动态设置的内联样式 CSS?

javascript - 如何在 javascript 中正确初始化 ErrorEvent?