DEV Community

Harit Himanshu
Harit Himanshu

Posted on

1

What does event.waitUntil do in service worker and why is it needed?

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…

Top comments (1)

Collapse
 
sargalias profile image
Spyros Argalias

According to the MDN docs on ExtendableEvent.waitUntil() it prevents the service worker from terminating until the work inside the function is done. This is because the work inside the function is asynchronous, it could potentially take many seconds to complete.

Essentially it just waits for the promise to be fulfilled.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more