Kevin Powell - CommunityKP-C
Kevin Powell - Community5mo ago
2 replies
Faker

Web worker context vs browser/main "thread" context

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");
    })
  );
});

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?
Was this page helpful?