Web worker context vs browser/main "thread" context

fetch("/data.json").then(res => res.json()).then(data => {
console.log(data);
});
fetch("/data.json").then(res => res.json()).then(data => {
console.log(data);
});
Consider the above code, this is something that we write in the browser context, normal thread without any web workers. The browser already wait for the promise to be resolve. Now consider the following service worker script:
self.addEventListener("install", event => {
event.waitUntil(
caches.open("my-cache").then(cache => {
return cache.add("/index.html");
})
);
});
self.addEventListener("install", event => {
event.waitUntil(
caches.open("my-cache").then(cache => {
return cache.add("/index.html");
})
);
});
Notice that here, we need to explicitly use the event.waitUntil() function to tell the service worker not to "kill" itself too quick. My question is, why do we need to use the event.waitUntil() function, why the service worker doesn't wait kind of "indefinitely" just like in browser/main thread context?
2 Replies
13eck
13eck3mo ago
This is primarily used to ensure that a service worker is not considered installed until all of the core caches it depends on are successfully populated.
https://developer.mozilla.org/en-US/docs/Web/API/ExtendableEvent/waitUntil From what I'm reading on MDN, it's because once the install event is over the service worker will be installed. So the worker needs to, well, wait until the callback is completed before finishing the install process. If you don't wait then once the install callback completes—regardless of the result of the promise—the service worker will be installed and, in your example, the cache won't be populated. Think of it like await but for the entire event. And it needs to be used b/c otherwise the event itself won't know what happens outside the context of the event. Remember that events are reactive and passive. They just happen. The install event needs a way to know if the setup succeeds or not, hence the method on the event itself.
Faker
FakerOP3mo ago
yeah, also, service workers run in the background, the browser don't really has any cue of when it will finish, no?

Did you find this page helpful?