event.waitUntil在服务工作者中做了什么以及为什么需要它? [英] What does event.waitUntil do in service worker and why is it needed?

查看:284
本文介绍了event.waitUntil在服务工作者中做了什么以及为什么需要它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

MDN suggests that you do the following to create and populate service worker cache:

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

我不明白那段代码。还记录了 waitUntil 方法,看来上面的代码是目前存在的唯一目的:

I do not understand that code. The waitUntil method is documented too, and it seems the code above is the single purpose of it's existence at the moment:

ExtendableEvent.waitUntil()方法延长了
事件的生命周期。在与安装事件关联的EventHandler中调用时,
会延迟将安装工作者视为已安装,直到传递的
Promise成功解析为止。这主要用于确保在填充所依赖的所有核心
缓存之前,不会考虑安装
服务工作者。

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 一般会影响代码流吗?是否会阻止事件传播直到它的承诺结算?

  • 为什么在打开工作缓存的上下文中需要它?

  • How does waitUntil generally affect code flow? Does it stop event from propagating until it's promise resolves?
  • Why is it needed in the context of opening worker cache?

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

I am asking this question because I have problems with the code above and I would like to understand it.

推荐答案

如描述所示, ExtendableEvent.waitUntil()方法延长了事件的生命周期。如果您不在方法中调用它,则可以随时停止服务工作者(请参阅规范)。

As the description says, the ExtendableEvent.waitUntil() method extends the lifetime of the event. If you don't call it inside a method, the service worker could be stopped at any time (see the specification).

因此, waitUntil 方法用于告诉浏览器不要终止服务工作者,直到传递给 waitUntil 的承诺被解决或拒绝。

So, the waitUntil method is used to tell the browser not to terminate the service worker until the promise passed to waitUntil is either resolved or rejected.

关于您的具体问题:


  • 如果安装激活事件,它将服务工作者的状态切换延迟到已安装已激活(请参阅 waitUntil方法的规范,特别是段落的最后部分) 。

  • 我认为我的答案的其余部分已经回答了为什么需要它。

  • In the case of the install and the activate events, it delays the state switch of the service worker to installed and activated (see the specification of the waitUntil method, in particular the last part of the paragraph).
  • I think the rest of my answer already answered as to why it is needed.

这篇关于event.waitUntil在服务工作者中做了什么以及为什么需要它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆