Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
182
rated 0 times [  185] [ 3]  / answers: 1 / hits: 25641  / 8 Years ago, sat, june 18, 2016, 12:00:00

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 ...
]);
})
);
});


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:




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.




What I do not understand is:




  • 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.


More From » promise

 Answers
4

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).


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.


About your specific questions:



  • 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.


[#61719] Thursday, June 16, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leighm

Total Points: 423
Total Questions: 101
Total Answers: 112

Location: Turkmenistan
Member since Sat, Apr 16, 2022
2 Years ago
;